Bash script awkwardness with pwd

Vasiliy Stavenko picture Vasiliy Stavenko · Sep 24, 2013 · Viewed 33.1k times · Source

I've got a strange issue while working with a bash script. Here it is:

PWD=${pwd}
# several commands
cd /etc/nginx/sites-enabled/
# more commands
cd $PWD
# I expect that I returning to my directory, 
# but $PWD contains current dir - /etc/nginx/sites-enabled/

This behavior is kind of lazy. $PWD stores command, which calculates the current directory and returns it at the moment we call $PWD, but I want to store the string variable in it. How to do that?

Answer

Toam picture Toam · Sep 24, 2013

PWD is an environmental variable and is changed when you change the directory.

Use a different name for the variable,

eg:

MYPWD=${PWD}  #or MYPWD=$(pwd)
cd /etc/nginx/sites-enabled/
cd $MYPWD