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
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.
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:
#!/bin/bash
line.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.