Restore 'cd ..' functionality after following a symbolic link
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/
?
Solution 1:
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.
Solution 2:
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
-
$dir1
, ifcd -P ..
doescd ..
first andcd -- "$(readlink -f)"
afterwards, or -
/tmp
, ifcd -P ..
doescd -- "$(readlink -f)"
first andcd ..
afterwards.
In fact it does the latter, meaning that pwd
is intuitively two levels higher than the "parent" directory.
Solution 3:
An alternative way is to run:
cd $(/bin/pwd)/..