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.
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:
[email protected]:~$ pwd /home/greys
If I then use cd command to visit some other directory, pwd command will help me confirm it:
[email protected]:~$ cd /tmp [email protected]:/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:
[email protected]:/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:
[email protected]:~/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:
[email protected]:~/proj/bash$ cd /home/greys/
… the script will thank me for it:
[email protected]:~$ 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!