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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#!/bin/bash

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

# Check if SCRIPT_DIR is empty or not
if [ -z "$SCRIPT_DIR" ]; then
  echo "Failed to determine the script directory."
  exit 1
fi

# Now, you can use SCRIPT_DIR for your operations
echo "The script is located in the directory: $SCRIPT_DIR"

Here’s a breakdown of what this script does:

  1. #!/bin/bash: This line specifies that the script should be interpreted using the Bash shell.

  2. 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 the SCRIPT_DIR variable.

  3. if [ -z "$SCRIPT_DIR" ]; then: This line checks if SCRIPT_DIR is empty, indicating that the script failed to determine its directory.

  4. echo "The script is located in the directory: $SCRIPT_DIR": If SCRIPT_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.

0%