This short tutorial will demonstrate how to get the path to the currently running Bash/Shell script in Linux, and provide a code example.
Getting the path to the current script is useful if you have other files in the same directory as the script that you want to access when calling the script from elsewhere. For example, you may have a script that plays music located with your music files, and have a second script on your Desktop that calls it. The first script will need to find its own absolute path to be able to find where the music files are located.
Simplest Way to Get the Current Scripts Path
If the realpath command is available on your system, it can be used to get the path to the currently running script, from within the script, by running:
SCRIPT=$(realpath "$0") SCRIPTPATH=$(dirname "$SCRIPT")
If realpath is not available on your system, there is a workaround courtesy of user t-j-crowder on StackOverflow (Visit the link to get an explanation, it’s a good bit of scripting):
SCRIPTPATH="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
While there are other ways of getting the path to the currently running script, these two methods are the most reliable and reproducible.