Month: August 2026

How to query the name and directory of a Bash script

Once in a while, a Bash script needs to query its own name and directory. Here is an example on how to do that:

#!/usr/bin/bash

ThisScriptsName="$(basename -- "${BASH_SOURCE[0]}")"
ThisScriptsDirectoryAndName="$(readlink -f -- "${BASH_SOURCE[0]}")"
ThisScriptsDirectory="$(dirname -- "$ThisScriptsDirectoryAndName")"
TheCurrentDirectory="$(pwd)"

printf 'ThisScriptsName: %s\n' "$ThisScriptsName"
printf 'ThisScriptsDirectoryAndName: %s\n' "$ThisScriptsDirectoryAndName"
printf 'ThisScriptsDirectory: %s\n' "$ThisScriptsDirectory"
printf 'TheCurrentDirectory: %s\n' "$TheCurrentDirectory"

#EOF

Let’s assume the name of the file is WhatsMyNameAndLocation, and it is located in /usr/scripts and executed from / with /usr/WhatsMyNameAndLocation:

ThisScriptsName: WhatsMyNameAndLocation
ThisScriptsDirectoryAndName: /usr/scripts/WhatsMyNameAndLocation
ThisScriptsDirectory: /usr/scripts
TheCurrentDirectory: /

(Last update on August 8, 2026 was done by Editor F.)