BASH_SOURCE#

BASH_SOURCE is an array variable that contains the source filenames where the corresponding shell function or script is defined.

${BASH_SOURCE[0]} vs $0#

While $0 is often used to get the name of the script, it behaves differently depending on how the script is invoked. ${BASH_SOURCE[0]} is more reliable for finding the actual file path.

Context$0${BASH_SOURCE[0]}
Interactive Shell-bash(empty)
Executing Script (./app.sh)./app.sh./app.sh
Sourcing Script (source app.sh)-bashapp.sh

Why use ${BASH_SOURCE[0]}?#

When a script is sourced (using source or .), $0 remains the name of the calling shell (eg. -bash), whereas ${BASH_SOURCE[0]} correctly points to the script being sourced. This makes it the standard way to determine the script’s directory regardless of how it was executed.

Common Pattern: REPO_ROOT#

Use this snippet to get the absolute path of the directory where the script resides:

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

Call Stack: BASH_SOURCE[1], [2], ...#

BASH_SOURCE is an array that represents the call stack.

  • ${BASH_SOURCE[0]}: The file currently being executed/sourced.
  • ${BASH_SOURCE[1]}: The file that called or sourced ${BASH_SOURCE[0]}.
  • ${BASH_SOURCE[2]}: The file that called ${BASH_SOURCE[1]}, and so on.

This is particularly useful for debugging or logging in complex script architectures involving multiple sourced files and functions.