Is it better to use $(pwd) or $PWD?

If bash encounters $(pwd) it will execute the command pwd and replace $(pwd) with this command's output. $PWDis a variable that is almost always set. pwd is a builtin shell command since a long time.

So $PWD will fail if this variable is not set and $(pwd) will fail if you are using a shell that does not support the $() construct which is to my experience pretty often the case. So I would use $PWD.

As every nerd I have my own shell scripting tutorial


It should also be mentioned that $PWD is desirable because of its performance. As a shell variable, it can be resolved almost instantly. $(pwd) is a bit more confusing. If you inspect man 1 bulitin on a system with Bash, you'll see that pwd is a built-in command, which may lead you to believe that it will be just as fast as accessing a variable. However, the $() construct always launches a new subshell (a new process) to run its contents, regardless of what's inside. The same thing goes for backticks. Indeed, when I benchmark it:

echo 'Benchmarking $(pwd)...'
time (for i in {1..1000}; do echo $(pwd) > /dev/null; done)
echo 'Benchmarking $PWD...'
time (for i in {1..1000}; do echo $PWD > /dev/null; done)

I get 1.52 seconds for the $(pwd) call and 0.018 seconds for $PWD. Unnecessary launching of subshells, as well as any other extraneous processes, should be avoided whenever possible. They're much more expensive than function calls that you may be used to in other languages.