I have been trying to figure out how a shell knows which directory you're currently in. I know there is an environment variable $PWD
but when I try changing it manually, it changes what my shell shows at the prompt but commands like ls
and cd
are unaffected.
cd
is an internal shell command so I can understand it might use info stored within the shell memory, but ls
is external and yet running ls
without anything will give me whatever directory I was originally in regardless what I do to $PWD
.
Each process has its own individual current working directory which the Linux system tracks. This is one of the pieces of information the OS manages for each process. There is a system call getcwd()
which retrieves this directory.
The $PWD
environment variable reflects what getcwd()
was the last time the shell checked, but changing it does not actually change the current directory. To do that the shell would have to call chdir()
when $PWD
changes, which it does not do.
This also is the reason cd
has to be a shell built-in. When you run a sub-process that child process gets its own working directory, so if cd
were an executable then its calls to chdir()
would be useless as that would not change its parent's working directory. It would only be changing its own (short-lived) working directory. Hence, cd
is a shell built-in to avoid a sub-process being launched.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With