Get the current directory in a Bash script
October 31, 2020 ‐ 2 min read
When scripting together a bash script you might need to know your current working directory at some point.
The current working directory is conveniently stored in the variable $PWD
which is available in all POSIX compliant shells. Another option to get the current working directory is by using the pwd
command. That pwd
command is a shell builtin and available in all POSIX compliant shells as well.
#!/bin/bash
# Option 1
cd /home/koen
echo $PWD
# Option 2
cd /home/koen/Test
CWD=$(pwd)
echo $CWD
When we run this script it produced the following output. The first output being the value of $PWD
. The second line being the output of $(pwd)
.
$ bash print_cwd
/home/koen
/home/koen/Test
What about symlinks?
The example shown before doesn't take into account symlinks. So if you run pwd
or $PWD
in a folder that is symlinked it doesn't show you the physical location but the location of the symlink.
If you need the actual physical location of the directory in your script you can use the -P
option on the pwd
command.
That /home/koen/Test
folder was actually a symlink to another location. Lets alter the script to take symlinks into account.
#!/bin/bash
# In a symlinked folder
cd /home/koen/Test
CWD=$(pwd)
echo $CWD
# Also in a symlinked folder
cd /home/koen/Test
CWD=$(pwd -P)
echo $CWD
And lets run it.
$ bash print_cwd
/home/koen/Test
/home/koen/Documents/Test
Now as you see, the pwd -P
command outputs the physical location of the Test
folder.
Learning more
The best way to learn more is to use Bash. A lot. Don't forget that Google is your friend.
In case you learn well from books I would recommend these.