Home » Linux » Shell » How to Get the Path to the Current Bash/Shell Script

How to Get the Path to the Current Bash/Shell Script

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.

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment