Any linux shell script can be run from any folder by specifying a relative path to the script on the command line. This ability is convenient when a script in a different folder needs to be run. Instead of switching to the folder, running the script and then switching back, the relative path can be used to run the script, as in the following example:
Three commands using cd
> cd ..
> cd –
One command using a relative path
Using just one command is quicker for scripts that are run frequently, however the script might behave differently if it relies somehow on the current directory. For scripts that rely on a specific current directory, it is usually possible to write the script so that it automatically changes to that directory when it’s run. This can be done by hard-coding the directory in the script, or by detecting which directory the script is in. The second method is more generally useful because it can be re-used (copied) from other scripts without any modification. The following example demonstrates one way this can be done:
echo “SCRIPT_DIR: $SCRIPT_DIR”
This script fills out two environment variables when it starts: START_DIR and SCRIPT_DIR. START_DIR contains the directory where the user started the script from, and SCRIPT_DIR contains the directory where the script is located. The script first switches to SCRIPT_DIR so it can do whatever processing it needs to do from there, and then switches back to START_DIR before it exits.