When we cd into a dir via its softlink, i observe:

  1. ls .. will show the content of the parent dir of the linked dir, while cd .. will go under the parent dir of the softlink. Why are they different?

  2. cd .. followed by tab doesn't give any options for completion, neither for the content of the parent dir of the linked dir, nor for the content of the parent dir of the softlink. Why is it that?

  3. How do we know, among all the directory commands, which work for the linked dir, or for its softlink, in the above situation?

  • 1
    Can't claim to have an answer for that, but I know that cd can be made to behave according to the "physical" location it's in (i.e. the linked-to dir) via the -P switch. At least that's how it is for Bash. – Joseph R. Sep 29 '14 at 2:59
  • If you need to be certain of your location you're best off using full paths at all times. If you need to change directory in a script and return to the start, store it as a variable first with $(basename $(readlink -f $0)) or $(pwd) or wherever you want to run things, and base locations off of that instead of assuming .. will do what you want. It will also be more compatible with other shells that might have different behaviour yet again. – Justin Sep 29 '14 at 3:27

Because bash (and possibly other shells) track the path you descended, including symlinks, in order to make your trail back up look like the one down.

Bash knows how you got to the working directory because cd must be a shell built-in. When you run ls .. the shell can't substitute the "symbolic path" because grep .. is also valid and translating .. would be terribly confusing.

As it is, the shell currently has two interpretations of .. which could be argued is as confusing as if it never tried to help at all.

| improve this answer | |
  • 1
    .. should be the parent directory of the directory you are in (and should be stored in the inode of the directory you are currently in). There should be no ambiguity. However I do like bash behaviour as I more often want to go back to the directory the link was in (but cd - is often enough to do that, though... and pushd/popd could help if we remember to use them). Imo, default should be to go to physical parent dir, and an option allow to go back to the link's dir (that it is reversed could be for some compatibility/other clever reason?) – Olivier Dulac Sep 29 '14 at 9:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.