Bash Script to Get the Directory of the Script File
In Bash scripting, it’s often useful to determine the directory where the script file is located. This can be particularly important if your script needs to access other files or resources relative to its own location. Here’s a Bash script snippet that accomplishes this task:
|
|
Here’s a breakdown of what this script does:
-
#!/bin/bash
: This line specifies that the script should be interpreted using the Bash shell. -
SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &> /dev/null && pwd)
: This line uses a combination of commands to determine the directory of the currently executing script. Let’s break it down step by step:-
${BASH_SOURCE[0]}
: This variable represents the path to the currently executing script. -
dirname -- "${BASH_SOURCE[0]}"
: This extracts the directory path containing the script file. -
cd -- "$(dirname -- "${BASH_SOURCE[0]}")"
: This changes the current working directory to the script’s directory. The--
is used to handle directory names that start with dashes. -
pwd
: This command then prints the current working directory, which is now the script’s directory, and stores it in theSCRIPT_DIR
variable.
-
-
if [ -z "$SCRIPT_DIR" ]; then
: This line checks ifSCRIPT_DIR
is empty, indicating that the script failed to determine its directory. -
echo "The script is located in the directory: $SCRIPT_DIR"
: IfSCRIPT_DIR
is not empty, it prints the directory where the script is located.
You can now use the $SCRIPT_DIR
variable for any operations that require the script’s directory.