For convenience, there are times you may want to run a shell script that changes your current working directory to another directory. For example, if you frequently visit your projects directory(~/Projects) and want to quickly navigate there, you can write a Bash script to do so.
In this guide, I'll explain how you can change directory in Linux shell scripts using the cd command. I will also explain some complexities of how cd behaves along the way.
Let's start with a script that navigates to the ~/Projects directory. We'll call it chdir.sh:
#!/usr/bin/bash
# Filename: chdir.sh
# change our current directory to ~/Projects
cd /home/traw/Projects
#print working directory
pwd
# print the PID of the shell running our script
echo $$
Let's understand our code:
The "$$" is a Bash internal variable that contains the Process ID (PID) of the shell running your script.
[traw@sysxplore][$] bash chdir.sh
/home/traw/Projects
118922
[traw@sysxplore][$]
As we can see, running our script produces the expected output of "/home/traw/Projects" as well as the shell's process ID.
Let's see what directory we're in now that we've run the script.
[traw@sysxplore][$] bash chdir.sh
/home/traw/Projects
118922
[traw@sysxplore][$] pwd
/home/traw
[traw@sysxplore][$]
This is not what we expected because the current directory has not been changed to /home/traw/Projects. So, what may be the problem?
Let's look at our shells' process ID: