What's the difference between unix built-in `pwd` command and it's $PWD environment variable?

StackOverflow https://stackoverflow.com/questions/4362643

  •  09-10-2019
  •  | 
  •  

Question

Here's the case. I have a directory call :- %/home/myname/

I did a soft link in that directory:- %cd /home/myname/ %ln -s /home/others/ .

Now, I cd into others/ from /home/myname/ Here's the interesting part.

When I did a unix built-in pwd command, i get the ORIGINAL path name:- %/home/others/

But when i echo the $PWD environment variable, i get the link path name:- %/home/myname/others/

Why is that so?

Was it helpful?

Solution

/var# ls -l
lrwxrwxrwx  1 root root   10 Aug 22 13:21 mail -> spool/mail
drwxr-xr-x  2 root root 4096 Jul  1 20:58 opt
drwxr-xr-x 22 root root 4096 Dec  5 17:38 run
drwxr-xr-x 12 root root 4096 Aug 22 13:21 spool
drwxrwxrwt 14 root root 4096 Dec  6 02:46 tmp
/var# cd mail
/var/mail# echo $PWD
/var/mail

/var/mail# pwd
/var/mail

/var/mail# /bin/pwd
/var/spool/mail

In other words, using $PWD is sufficient, because pwd might not give you better results (for any definition of better) anyway.

Why that is? /bin/pwd uses OS-specific calls to determine the current working directory - and in case of Linux, the kernel only keeps the resolved directory (see /proc/self/cwd), whereas the shell's pwds contain what the shell thinks it is in.

OTHER TIPS

The difference between the /bin/pwd external command and the built-in is that the external command doesn't know what set of cd operations got you there and therefore doesn't pretend that your current directory is somewhere down a chain of symlinks; it gives you the direct path from root to your current directory, rather like the realpath() function would.

See set -o physical in bash.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top