4

Say you have directory ~/mytool that softlinks to /usr/local/mytool. Then cd mytool leaves your current directory as ~/mytool, which may cause scripts to behave incorrectly. Is there a way to avoid this behaviour?

With some googling, I see that you can achieve this as follows:

cd $1 ; cd `pwd -P`

Is there no switch to 'cd'? Environment variables?

Steve Bennett
  • 5,750
  • 12
  • 47
  • 59

3 Answers3

8

If you type set -P in bash all commands such as cd, pwd will follow the physical path. Else you can use cd -P and pwd -P for temporary changes to the default behavior.

From the manpage of bash:

          -P      If  set,  the shell does not follow symbolic links when executing commands such as cd that change the cur-
                  rent working directory.  It uses the physical directory structure instead.  By default, bash  follows  the
                  logical chain of directories when performing commands which change the current directory.

To make this permanent, put it in your ~/.bashrc file, for example.

Mattias Ahnberg
  • 4,139
  • 19
  • 19
4

"cd" is a built in in most shells. In bash, you can get the behavior you want by adding

set -P

in a startup script (.bashrc, say).

malcolmpdx
  • 2,300
  • 1
  • 16
  • 12
2

On Ubuntu/Debian (not sure about BSD), cd -P symlink puts me in the resolved symlink path. (Same behavior as pwd -P)

Tested using:

mkdir a
ln -s a b
cd -P b && pwd
thinice
  • 4,716
  • 21
  • 38