How to Check if Script is Called from Terminal or Sourced from Other Scripts in Bash

The aim of this page📝 is to find an idiom in Bash that runs the code if called from a terminal, and loads the code if sourced from other script.This method mimics Python’s if __name__ == "__main__": idiom for conditional script execution in Bash.

Pavol Kutaj
1 min readMar 4, 2024
function print_single_nomad_job() {
nomad_url="$1"
job=$(basename "$nomad_url")
timestamp=$(date +%Y-%m-%d-%H-%M-%S)
#... irrelevant
}
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then print_single_nomad_job "$1"; fi
  • ${BASH_SOURCE[0]} in Bash stores the name of the script being sourced or executed.
  • ${0} is a special variable in Bash that contains the name of the current script.
  • Comparing ${BASH_SOURCE[0]} with ${0} helps determine if a script is being executed directly or sourced.
  • When ${BASH_SOURCE[0]} is equal to ${0}, it indicates that the script is being executed directly from the terminal.

ANKI

  • Question: What does ${BASH_SOURCE[0]} store in Bash?
  • Answer: The name of the script being sourced or executed.
  • Question: How can you check if a Bash script is being executed directly or sourced?
  • Answer: By comparing ${BASH_SOURCE[0]} with ${0} in an if statement.

--

--

No responses yet