pwd command and PWD variable

PWD variable PWD variable

pwd command, and you probably know, reports the current working directory in your Unix shell. PWD stands for Present Working Directory. In addition to pwd, there’s also a special variable – one of the user environment variables – called PWD, that you can also use.

pwd command

Just to remind you, pwd command is a super simple way of confirming where you are in the filesystem tree.

Usually, your shell session starts in your home directory. For me and my username greys, this means /home/greys in most distributions:

greys@xps:~$ pwd
/home/greys

If I then use cd command to visit some other directory, pwd command will help me confirm it:

greys@xps:~$ cd /tmp
greys@xps:/tmp$ pwd
/tmp

PWD environment variable

Most Unix shells have PWD as a variable. It reports the same information as pwd command but saves children processes the trouble of using pwd command and getpwd system call just to confirm the working directory of their parent process.

So, you can just do this to confirm $PWD value:

greys@xps:/tmp$ echo $PWD
/tmp

… which really helps in shell scripting, cause you can do something like this:

#!/bin/bash
echo "Home directory: $HOME"
echo "Current directory: $PWD"

if [ $HOME != $PWD ]; then
    echo "You MUST run this from your home directory!"
    exit
else
    echo "Thank you for running this script from your home directory."
fi

When we run this, the script will compare standard $HOME variable (your user’s homedir) to the $PWD variable and will behave differently if they match.

I’ve created and saved pwd.sh in my projects directory for bash scripts: /home/greys/proj/bash:

greys@xps:~/proj/bash$ ./pwd.sh 
Home directory: /home/greys
Current directory: /home/greys/proj/bash
You MUST run this from your home directory!

If I now change back to my home directory:

greys@xps:~/proj/bash$ cd /home/greys/

… the script will thank me for it:

greys@xps:~$ proj/bash/pwd.sh
Home directory: /home/greys
Current directory: /home/greys
Thank you for running this script from your home directory.

Have fun using pwd command and $PWD variable in your work and shell scripting!

See Also




Keep Learning with Me

Follow me on Facebook and Twitter or jump into Telegram chat!:
I'm using Brave browser
Give it a try, it's awesome: Brave Browser
IT Consultancy
I'm a principal consultant with Tech Stack Solutions. I help with cloud architectrure, AWS deployments and automated management of Unix/Linux infrastructure. Get in touch!
Recent Articles
28 May 2020

Raspberry Pi 4 8GB

19 May 2020

Grafana 7.0 Released

13 May 2020

OpenIndiana 2020.04 Released

Recent Tweets