Get Script Directory in Bash
Fumbani Banda
Nov 30, 2021

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.
#!/bin/bash
DIR="$(dirname "${BASH_SOURCE[0]}")"
DIR="$(realpath "${DIR}")"
echo $DIR
The output below shows that the script prints out its absolute path.
Author: Fumbani Banda
Related Article - Bash Script
Related Article - Bash Directory
- Run Mkdir Only When the Directory Does Not Exist
- Change Directory in Bash
- Find the Current Folder Name in Bash
- Bash Create Directory
- Find Files and Folders in Linux
- List Directories in Bash