13

If I create a symbolic link in the terminal with a command like

ln -s /path/to/some/directory symbolicLink

and then follow the link with

cd symbolicLink

the terminal appears to think that the cwd is ~/symbolicLink/ even though it is actually showing ~/path/to/some/directory/ (assuming that the link was made in ~, of course). What this means is that if I then type cd .. I am taken back to ~, because the terminal 'thinks' this is the parent of the cwd.

What would I need to change such that cd .. would instead take me to ~/path/to/some/, i.e. the real parent of ~/path/to/some/directory/?

4 Answers 4

15

See https://stackoverflow.com/questions/10456784/behavior-of-cd-bash-on-symbolic-links.

You can use 'cd -P' to go to the "real" parent directory. See the first comment on the top answer on how to make this the default behavior.

5

There's a subtle caveat in the cd -P behaviour (posted as answer because of the length):

$ dir1=$(mktemp --directory)
$ dir2=$(mktemp --directory)
$ ln -s -- "$dir1" /tmp/start
$ ln -s -- "$dir2" "$dir1"
$ cd "/tmp/start/"*
$ cd -P ..

What should pwd print now? Logically, it could be either

  1. $dir1, if cd -P .. does cd .. first and cd -- "$(readlink -f)" afterwards, or
  2. /tmp, if cd -P .. does cd -- "$(readlink -f)" first and cd .. afterwards.

In fact it does the latter, meaning that pwd is intuitively two levels higher than the "parent" directory.

1
  • 1
    Thanks! cd -P still solves the issue I was facing, but is still useful to know.
    – Val
    Aug 14, 2013 at 4:22
2

An alternative way is to run:

cd $(/bin/pwd)/..
2

I feel your pain—I consider bash to be basically broken for interactive use because of this behavior.

tcsh is a far more user-friendly shell for interactive use. Leave bash for programming (if you insist on writing shell scripts when there are much better alternatives among the many scripting languages).

To change shells for any user, type chsh at the command line and follow the prompts (again, I recommend /bin/tcsh and the excellent O'Reilly book Using csh and tcsh, available for next to nothing used).

1
  • Since I wrote this answer, I've learned to stop worrying and love Bash for interactive use. But I still can't deal with the default cd behavior for symlinks. I have to remember to put set -o physical in my .bashrc or .bash_profile for every machine I use. May 29, 2015 at 20:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .