Think of directories as little files, essentially lists or tables.
The reason why a directory "knows" its parent directory is because behind the curtains, the full directories are used. As a convenience, links to the upper and current directory exist in every directory.
A symbolic link to a directory is like a link to a file. Once "inside" that linked directory, you're in that linked directory, and the ..
and .
are hardlinks to the parent and current (real) directory, the information that you've "came via" that symlink (or which one, rather) is technically lost.
When creating a new directory, those three hardlinks are always created, at least on unixoidal systems (there are some older Unices that allowed arbitrary hardlinks though).
However, shells contain a lot of "convenience sugar". The shell will remember for you that actually you came from a symlink, and it'll "rewire" relative directories like that for you.
The shell builtin pwd
is also aware of that, works in this manner. The /usr/bin/pwd
application will simply state the fully qualified path, i.e. the one that isn't through symlinks. If it didn't, there would be many possible ways to reach that directory, and technically speaking all those combinations (which can be infinite, if you have circular symlinks) would have to be printed.
Most (though probably not all, I don't know for sure) shell's cd
command has the option -P
, which when entering a directory through a symlink, will use the physical directory structure, rather than following symlinks. You can read about it in the man page of "bash_builtins" (easy to reach through man cd
inside bash
).
Here's an excerpt from man zshbuiltins
:
If the -P option is given or the CHASE_LINKS option is set, symbolic links are resolved to their true values. If the -L option is given symbolic links are retained in the directory (and not resolved) regardless of the state of the CHASE_LINKS option.
(the man page of bash contains a similar section)
You might want to have a look at a really minimal shell, like s
. I'm not suggesting you should use it as a daily shell, but it's so minimal, it relies on a lot of OS tools for anything other than the absolute basic things a command interpreter really provides for. It is a pretty good teaching tool in that regard.
pwd
to/bin/pwd
. The shell builtin command "lies". – Stephen Harris Sep 24 '21 at 23:55a
. There's only one subdirectory (asub
), and a directory only has one parent. – Boann Sep 25 '21 at 12:16pwd
prints/tmp/bb/b/bsub
, and presumablycd ..
goes to/tmp/bb/b/
, so yeah, expectingls ..
to also print the contents of/tmp/bb/b/
would seem relatively natural. – ilkkachu Sep 25 '21 at 13:46