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?
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.
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).
Bash (especially sh) is case- and space-sensitive.
#$ 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With