$PWD vs. pwd regarding portability

POSIX requires $PWD to be set in the following fashion:

PWD  

This variable shall represent an absolute pathname of the current working directory. It shall not contain any components that are dot or dot-dot. The value is set by the cd utility, and by the sh utility during initialization.

So you can rely on that being set – but do note "... an absolute path...", not the absolute path.

bash (at least recent versions) will remember what symlinks you followed when setting $PWD (and the pwd builtin). command pwd (that is, the external command) will not. So you'll get different results there, which might, or might not, be important for you. Use pwd -P if you want a path without symlinks.

Do note that the pwd documentation states:

If an application sets or unsets the value of PWD, the behavior of pwd is unspecified.

So, don't do that :)

In short, there is no winner here. The environment variable will be there in POSIX shells, as will the external command and possibly a built-in too. Choose the one that best fits your need, the important thing being whether you care about symlinks or not.


From that forum article, "$PWD vs `pwd`" which compares AIX 4.2.1, AIX 6, Sparc Solaris 10 and Redhat 5 enterprise with this regard:

  • there is no difference between $PWD and builtin pwd,

  • there is no difference between builtin pwd -P and /usr/bin/pwd.

The former shows working directory with names of symbolic links whereas the latter displays actual path.

The only discrepancy is that external command is in /usr/bin in most systems and /bin in Redhat.

Tags:

Bash