Command Line – Difference in Use Between pwd and $PWD

command line

To print current/present working directory environment variable $PWD and command pwd are available. So, What is difference in usage of both? or What should be chose for specific purpose?

Best Answer

That depends on what you're doing. First of all, $PWD is an environment variable and pwd is a shell builtin or an actual binary:

$ type -a pwd
pwd is a shell builtin
pwd is /bin/pwd

Now, the bash builtin will simply print the current value of $PWD unless you use the -P flag. As explained in help pwd:

pwd: pwd [-LP]
Print the name of the current working directory.

Options:
  -L    print the value of $PWD if it names the current working
    directory
  -P    print the physical directory, without any symbolic links

By default, `pwd' behaves as if `-L' were specified.

The pwd binary, on the other hand, gets the current directory through the getcwd(3) system call which returns the same value as readlink -f /proc/self/cwd. To illustrate, try moving into a directory that is a link to another one:

$ ls -l
total 4
drwxr-xr-x 2 terdon terdon 4096 Jun  4 11:22 foo
lrwxrwxrwx 1 terdon terdon    4 Jun  4 11:22 linktofoo -> foo/
$ cd linktofoo
$ echo $PWD
/home/terdon/foo/linktofoo
$ pwd
/home/terdon/foo/linktofoo
$ /bin/pwd
/home/terdon/foo/foo

So, in conclusion, on GNU systems (such as Ubuntu), pwd and echo $PWD are equivalent unless you use the -P option but /bin/pwd is different and behaves like pwd -P.