What is the difference between $0 and $BASH_SOURCE?

01.2k

The difference between $0 and $BASH_SOURCE in a Bash script is as follows:

  • $0: This variable represents the name of the script as it was invoked. It reflects the command used to run the script, which can include a relative or absolute path. If the script is sourced (rather than executed), $0 will still show the name of the script that was called.

  • $BASH_SOURCE: This variable is an array that contains the source file names of the currently executing script or function. It is particularly useful when dealing with sourced scripts or functions, as it provides the path of the script that is currently being executed, even if it was sourced from another script. The first element, ${BASH_SOURCE[0]}, will give you the name of the script that is currently running.

In summary, $0 is used for the script name as invoked, while $BASH_SOURCE provides the source file names, especially useful in nested or sourced scripts.

0 Comments

no data
Be the first to share your comment!