You know how to make a shell script and make it executable. Now you want the script to change the current directory in the terminal but it doesn't work. Why is that?

cd command does not work in a shell (batch) script in the terminal.

The terminal usually starts in your user directory. Often you want to work in a different directory and you write a shell script to change the directory to ~/a/b/c like this:

#!/bin/bash
cd ~/a/b/c

You saved the file as ~/cdtest and made it executable with the command:

chmod +x ~/cdtest

You can now execute the script with the command:

./cdtest

cd into directory does not work?

When you execute the script, nothing happens! Or so it seems. What happened is that the cdtest script is run in a new shell process. The cd command succeeds but when the script is done, the shell is back where it started before executing the script. This situation is good when you don’t plan to interact with the terminal after executing the script. But if you want to change the directory and then work in that directory, you might want to source the script.

Source the script

The alternative of executing a shell script, is sourcing the script. Sourcing the script will execute the commands in the current shell process.

There are two advantages here:

  1. You don’t need to make the script executable
  2. You don’t need the #!/bin/bash line.

Solution example

Rewrite script cdtest like this:

cd ~/a/b/c

You cannot execute this script, but you can source the script with this command:

. ./cdtest

Or this command:

source cdtest

Both commands will run the commands from your script in the current shell.

You might have to check if your OS supports the source command. I tested this on macos where it works.

Written by Loek van den Ouweland on 2020-08-16.
Questions regarding this artice? You can send them to the address below.