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

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

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

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

echo "Home directory: $HOME"
echo "Current directory: $PWD"

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

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 in my projects directory for bash scripts: /home/greys/proj/bash:

greys@xps:~/proj/bash$ ./ 
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/
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

Follow me on Facebook, Twitter or Telegram:
I learn with Educative: Educative
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 Tweets