[BASH] Get the source directory of a bash script

Often it’s very useful declaring a variable with the absolute path of the bash script. In doing so, you can prepend that variable to other sub-path variables (e.g., a sub-dir “logs”).

But, how can we dynamically get the source directory of a bash script? And why is that better than manually writing the static path? That’s better because of this simple reason: if you move the script or rename one of the parent directory where the script is within, you have to remember to update your code as well. Instead, using the following bash string, the absolute path is automatically updated:

$(dirname "${BASH_SOURCE[0]}")

Let’s see a common example where you can use the above code:

#!/bin/bash
TODAY=$(date +"%Y%m%d")
HOSTNAME=$(hostname)

ABSOLUTE_PATH=$(dirname "${BASH_SOURCE[0]}")
FILE_LOG="${ABSOLUTE_PATH}/logs/test.log"

echo "${TODAY} ${HOSTNAME}: Test QWERTY" >> ${FILE_LOG}

Leave a Reply