Get Script Directory in Bash

Fumbani Banda Nov 30, 2021
Get Script Directory in Bash

This tutorial demonstrates getting the script’s directory using the dirname command and the realpath command.

Get Script Directory in Bash

The dirname command is a Linux command that removes the file name, leaving the pathname of the directory that contains the file. The ${BASH_SOURCE[0]} is a variable that is used to get the script’s path in a sourced or directly executed bash script.

The realpath command expands all symbolic links and resolves references to /./, /../, and / characters in the null-terminated string named path to obtain the absolute path.


DIR="$(dirname "${BASH_SOURCE[0]}")"
DIR="$(realpath "${DIR}")"

echo $DIR

The output below shows that the script prints out its absolute path.

Get Script Directory in Bash

Fumbani Banda avatar Fumbani Banda avatar

Fumbani is a tech enthusiast. He enjoys writing on Linux and Python as well as contributing to open-source projects.

LinkedIn GitHub

Related Article - Bash Script

Related Article - Bash Directory