Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script awkwardness with pwd

Tags:

bash

cd

pwd

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?

like image 541
Vasiliy Stavenko Avatar asked Sep 24 '13 00:09

Vasiliy Stavenko


People also ask

What does PWD do bash?

The pwd Linux command prints the current working directory path, starting from the root ( / ). Use the pwd command to find your way in the Linux file system structure maze or to pass the working directory in a Bash script.

What does $() mean in bash?

Example of command substitution using $() in Linux: Again, $() is a command substitution which means that it “reassigns the output of a command or even multiple commands; it literally plugs the command output into another context” (Source).

Is bash space sensitive?

Bash (especially sh) is case- and space-sensitive.

What does #$ mean in bash?

#$ does "nothing", as # is starting comment and everything behind it on the same line is ignored (with the notable exception of the "shebang"). $# prints the number of arguments passed to a shell script (like $* prints all arguments). Follow this answer to receive notifications.


2 Answers

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
like image 145
Toam Avatar answered Oct 21 '22 13:10

Toam


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.

like image 30
EJK Avatar answered Oct 21 '22 11:10

EJK