Sometimes you want to run a bash script from any directory, especially when it
is placed or linked in a directory in the
$PATH environment and depends on
other files in the same folder. The problem is: If you use a relative path for
the other file, it will try to find the file in the current working directory.
If you use an absolute path, you cannot move it later. So it should know where
itself is running in order to get the correct file path.
For the impatient, here is a script example that can run from anywhere to print the content of file "help.txt" under the script's directory:
relative_path=`dirname $0` absolute_path=`cd $relative_path;pwd` cat "$absolute_path/help.txt"
First, it gets the relative directory. There are two situations:
If the script is supposed to be executed directly like
If the script is supposed to be "sourced" like
source script.sh, use:
Once it has the relative path, it's easy to get the absolute path:
This method is compatible with both Linux and Mac OS. However, it's not perfect.
It won't work if you have changed the
cd command to something else using alias
or function. Although it does not usually happen, in this case, you can use the
absolute_path=`readlink -m $relative_path`
This command only works in Linux, so you have to pick the way suits you best.
$absolute_path is the absolute path of the file being executed, so you can
use it to get other files which will be correct no matter the current working