Why doesn’t CD work in a Shell Script? How can I make CD work in a Shell Script?

If you have ever tried to run the current directory (CD) command inside your shell script you’ll notice it doesn’t work.

Example

#!/bin/bash
cd /home/$user/Documents/test-directory

This is because shell scripts run inside a subshell, and each subshell has its own concept of what the “current directory” is. In fact, it’s not that the cd doesn’t execute, it actually does but the minute it exits the subshell you’re back in the original shell and nothing changed.

The easiest way to get around this is to exit the script into a new bash. You do this by setting bash at the end of the script.

  #!/bin/bash
echo "Setting new directory in a new bash shell.."
cd /home/$user/Documents/test-directory
echo "You are now in a new bash shell, type 'exit' to leave"
bash

This will result in something like this:

[$user@box Documents]$ ./test.sh 
Setting new directory in a new bash shell..
You are now in a new bash shell, type 'exit' to leave
[root@box test-directory]$

This can be really helpful if you have specific directories you work in – maybe a Documents, Downloads, Working, Temp, etc… folder.

Sharing is caring!

Leave a Reply