Why does "ls .." show real parent content when I'm inside a symbolic link directory?
Solution 1:
Your shell tracks the symbolic links that led you to your current working directory. cd
is a shell builtin and help cd
states (example from bash
):
Options:
-L
force symbolic links to be followed: resolve symbolic links in DIR after processing instances of..
-P
use the physical directory structure without following symbolic links: resolve symbolic links in DIR before processing instances of..
[…]
The default is to follow symbolic links, as if-L
were specified.
You can try cd -P ..
and see the difference. Another example is pwd -L
and pwd -P
(while pwd
is also a shell builtin).
Note the default behavior can be changed by set -P
and set +P
. See help set
for more details.
On the other hand ls
is a separate executable that doesn't benefit from this tracking ability of your shell. However you can make it follow symbolic links with this trick:
(cd -L .. && ls -l)
Basically we use cd
to change the current working directory with respect to symbolic links (and I explicitly used the default -L
option for that), then invoke ls -l
. The &&
operator means ls
will be executed only if cd
succeeds. Parentheses ()
make all that is inside be executed in a subshell. This is the trick: cd
command affects this subshell only and in your main shell nothing changes, there's no need to cd
back.