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?

有帮助吗?

解决方案

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

其他提示

Try:

PWD=`pwd`

Or:

PWD=$(pwd)

Both expressions will execute the pwd command and store the command output in the shell variable PWD. There is plenty of discussion on the web about when to use each style. The one point that I recall is that the "$(cmd)" approach allows for nesting of commands, e.g.

CURRENT_BASENAME=$(basename $(pwd))  

Edit - It just occurred to me that PWD is a built in shell variable that always expands to the current working directory.

you may also find cd - usefull

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top