Bash source Command: $0 Can Not Determine Its Own Location

The $0 variable in a bash script refers to the name of the script itself. However, if the script is being sourced (i.e., run with the source command) rather than executed as a standalone script, $0 will not be able to determine its own location.

Here’s an example to illustrate this:

# script.sh
echo "Script name: $0"
echo "Script location: $(dirname "$0")"

If we run this script with the ./script.sh command, it will output:

Script name: ./script.sh
Script location: .

However, if we source the script with the . script.sh command, it will output:

Script name: script.sh
Script location:

In this case, the location of the script cannot be determined, because it is not being executed as a standalone script, but is instead being run within the current shell environment.

Leave a Comment