Blog Datasheets Home About me Clients My work Services Contact

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:

1
2
3
4
5
6
#!/bin/bash

# Get the directory of the currently executing script
SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &> /dev/null && pwd)

echo "The script is located in: $SCRIPT_DIR"

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:

  1. 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.

  2. dirname -- "${BASH_SOURCE[0]}": This command extracts the directory part of the path contained in BASH_SOURCE[0].

  3. cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &> /dev/null: This command changes the current directory to the one extracted by dirname, and &> /dev/null ensures that any error messages are suppressed.

  4. 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

1
2
3
4
5
#!/bin/bash

SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &> /dev/null && pwd)

echo "My script is running from: $SCRIPT_DIR"

Running the Script

If you run this script from anywhere in your file system, it will print:

1
My script is running from: /home/user/scripts

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.


➡️ Flow library


⬅️ Applying SOLID principles in your everyday coding


Go back to Posts.