[Linux] How to tell a bash script is sourced or executed?
In bash, a script can be both executed and sourced.
An example script as follows:
|
|
Distinguish between the two
To tell whether a script is being sourced or not, one
can use the test [[ "${BASH_SOURCE[0]}" == "$0" ]]
,
where ‘${BASH_SOURCE[0]}’ is the current script filename,
and ‘$0’ is the same if being executed but empty string ""
if sourced, as shown in the above code.
Some differences between sourcing and executing
-
export: the command
export
has no effect for the calling environment because it is executed in a sub-shell. To set variables in current environment, source the script. -
exit and return: calling ‘exit’ when sourcing a script will close the terminal, use ‘return’ instead.
References
- Discussion of ‘$BASH_SOURCE’ on stackoverflow: https://stackoverflow.com/questions/41837948/can-a-bash-script-determine-if-its-been-sourced
Last modified on 2021-06-03