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

  • I encountered BASEDIR=$(pwd) in a script.

    Are there any advantages or disadvantages over using BASEDIR="$PWD", other than maybe, that $PWD could be overwritten?

    @StéphaneChazelas Very interesting write up. I'm only halfway through and will continue, but as far as I understood it, it's better to use `$(pwd)`, because `$PWD` can become outdated in certain circumstances.

    only in some shells (not bash, dash, zsh or ksh93 for instance) will `pwd` potentially give you less stale information than `$PWD` in some corner cases. `$(pwd)` on the other hand doesn't work if the current directory ends in newline characters, means forking a process (except in ksh93) and use extra resources. My view is use `$PWD` of `$(pwd -P)`, it's not worth using `$(pwd)`.

    at the bottom there stephane mentions using `cd -P -- "$dir"`. if there is any doubt about the value of `$PWD` you can always `cd -P .` first. this may also be beneficial in that you also get whatever `$PWD` was before that in `$OLDPWD` and so can compare them afterward - and the next `cd ...; cd -` sequence will be sure to bring you back to where you are now.

  • 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

    I was under the impression that the `\`command\`` syntax was undesirable and `$(command)` is to be preferred. As far as I know the latter is POSIX compliant, but I'm not 100% sure.

    @Minix The `$()` is indeed specified by POSIX so outside the pre POSIX `/bin/sh` available on Solaris 10 and older and `csh` derived shells, I doubt many other mainstream shells lack that feature.

    @Minix: Here is a recent question on this site that illustrates one problem with using backticks instead of `$()`

    correct, instead of $() you could use backticks, but this will not be cascadable so I did not mention it

    Nice minimap on your tutorial....

License under CC-BY-SA with attribution

Content dated before 6/26/2020 9:53 AM