14

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?

totymedli
  • 23,114
  • 18
  • 109
  • 143
Vasiliy Stavenko
  • 1,116
  • 1
  • 12
  • 27

3 Answers3

35

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
Toam
  • 910
  • 1
  • 7
  • 11
3

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.

EJK
  • 11,784
  • 3
  • 34
  • 53
  • 1
    No. I was badly concentrated and didn't mention, that $PWD - is a system variable and ALWAYS points to current dir. `HPWD=$(pwd)` worked just fine. – Vasiliy Stavenko Sep 24 '13 at 00:59
  • When you edit, you should edit to correct the post, not use edit to make a comment at the end of your post. You should fix this to avoid downvotes. It's confusing to people who may not read the entire answer. – jmort253 Apr 28 '18 at 20:39
0

you may also find cd - usefull