G2Labs Grzegorz Grzęda
Determining the Path of the Currently Running Bash Script
March 30, 2023
Determining the Path of the Currently Running Bash Script
For beginner programmers working with Bash scripts, a common requirement is to find the directory where the current script is located. This can be especially useful when your script needs to access files relative to its own location.
How to Get the Script’s Directory
In Bash, you can use a combination of commands to reliably get the path of the script’s directory, regardless of where it’s being called from. Here’s an example script that does just that:
In this script, SCRIPT_DIR
is the variable that will hold the path of the script’s directory.
Breaking Down the Command
Let’s break down the command to understand how it works:
BASH_SOURCE[0]
: This is an array that contains the source paths used to invoke the current shell. The first element[0]
refers to the path of the current script.dirname -- "${BASH_SOURCE[0]}"
: This command extracts the directory part of the path contained inBASH_SOURCE[0]
.cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &> /dev/null
: This command changes the current directory to the one extracted bydirname
, and&> /dev/null
ensures that any error messages are suppressed.pwd
: Finally,pwd
(Print Working Directory) outputs the current directory, which is now the script’s directory.
Example Usage
Suppose you have a script named myscript.sh
located in /home/user/scripts
. When you run this script from any location, SCRIPT_DIR
will always be /home/user/scripts
.
Example Script
Running the Script
If you run this script from anywhere in your file system, it will print:
|
|
Conclusion
Understanding how to get the path of the running script is a fundamental skill in Bash scripting. It allows your scripts to be more flexible and portable, as they can be run from any location without worrying about relative paths to other required files or directories. By using the method outlined above, you can easily incorporate this functionality into your Bash scripts.