How to define pwd as a variable in Unix shell

Sathish picture Sathish · Dec 30, 2013 · Viewed 15.5k times · Source

I tried the following but it didn't work.

dir=$pwd
echo $dir

/bin/env/####/ --id --edition dir- $dir

I want to paste the current working directory into the above script.

Answer

janos picture janos · Dec 30, 2013

The current directory is already in a variable, called PWD, and it is automatically set by the shell:

echo "$PWD"

You could also:

dir=$(pwd)
echo "$dir"

Or you could use these in your script without storing in additional variables:

/bin/env/####/ --id --edition-dir "$PWD"
/bin/env/####/ --id --edition-dir "$(pwd)"

For your information: every time you change directory, whether in an interactive shell or a script, the shell sets the value of the PWD variable to the current directory, and the value of OLDPWD to the previous directory.

Well, usually. As @WilliamPursell pointed out, OLDPWD is not standard, so it might not be available in all shells.