Search code examples
linuxbashshelllscd

Why does `cd ..` reflect symlink traversal, whereas `ls ..`does not?


ls ..

means ‘list upper directorie’s files and directories.’

When I changed directory following a symbolic link, ls .. does not follow the symblic link. It just shows the real upper directory.

For example, when the directory structure is as follows,

r ┬ a - b - sub@
  └ sub

(sub@ is a symbolic link to sub directory)

ls ..command after cd a/b/sub gives files at r directory as I’m in r/sub. not b directory’s. But cd .. command takes me to b directory.

How can I use ls command to show files in directory b?


Solution

  • A directory doesn't know what symbolic link you used to get to it; .. is an actual directory entry that points to the real parent directory. But when you use the shell command cd .., bash cheats. It knows what path you used to get there (it's in $PWD), so it just removes the last component of that and changes to the resulting directory.

    You can use the same trick yourself for the benefit of other commands by using "${PWD%/*}" instead of ..:

    ls "${PWD%/*}"