cd command does not work in a shell (batch) script in the terminal.
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?
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:
cd into directory does not work?
When you execute the script, nothing happens! Or so it seems. What happened is that
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:
- You don’t need to make the script executable
- You don’t need the
cdtest like this:
You cannot execute this script, but you can source the script with this command:
Or this command:
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.