linuxunixpwd

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


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?


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.