When writing Bash scripts, it’s often necessary to determine the directory path where the script is located. This can be useful for various purposes, such as changing the working directory, reading or writing files, or executing other scripts.
In this tutorial, we’ll explore how to get the directory path of a Bash script from within the script itself.
Using dirname
and $0
One common approach is to use the dirname
command with the $0
variable, which represents the name of the script being executed. Here’s an example:
SCRIPT_DIR=$(dirname "$0")
echo "Script directory: $SCRIPT_DIR"
However, this method has some limitations. If the script is called using a relative path or a symbolic link, dirname
may not return the correct directory.
Using readlink
and $BASH_SOURCE
A more reliable approach is to use the readlink
command with the $BASH_SOURCE
variable, which represents the path of the script being executed. Here’s an example:
SCRIPT_DIR=$(dirname "$(readlink -f "$BASH_SOURCE")")
echo "Script directory: $SCRIPT_DIR"
This method works by resolving any symbolic links and returning the absolute path of the script.
Handling Relative Paths and Symbolic Links
If you need to handle relative paths or symbolic links, you can use a combination of cd
, dirname
, and readlink
commands. Here’s an example:
pushd . > /dev/null
SCRIPT_PATH="${BASH_SOURCE[0]:-$0}"
while [ -h "$SCRIPT_PATH" ]; do
cd "$(dirname "$SCRIPT_PATH")"
SCRIPT_PATH="$(readlink -f "$SCRIPT_PATH")"
done
cd "$(dirname "$SCRIPT_PATH")" > /dev/null
SCRIPT_DIR="$(pwd)"
popd > /dev/null
echo "Script directory: $SCRIPT_DIR"
This method works by changing the working directory to the script’s location, resolving any symbolic links, and then returning the absolute path of the script.
Best Practices
When getting the directory path of a Bash script, keep in mind the following best practices:
- Use
readlink
and$BASH_SOURCE
instead ofdirname
and$0
for more reliable results. - Handle relative paths and symbolic links by using a combination of
cd
,dirname
, andreadlink
commands. - Always test your code to ensure it works as expected in different scenarios.
By following these guidelines, you can write robust Bash scripts that accurately determine their directory path, regardless of how they’re called or executed.