How can I source multiple bash scripts into each others properly? How can I source multiple bash scripts into each others properly? shell shell

How can I source multiple bash scripts into each others properly?


Bash has the built-in $BASH_SOURCE variable, which is similar to $0, but - unlike the latter - correctly reflects the name of the running script even when sourced.

Thus, simply replacing $0 with $BASH_SOURCE in your scripts should be enough.


If you use sh instead of source, it will load up the environment as you expect, instead of executing the script in the same environment:

dn=$( dirname "$0" )sh "$dn/init/init.sh"

This change will cause the code to run in a subshell instead of the same shell. You won't be able to do this for a script that needs a function from an outer shell, since you will still need to source that to have access to the function. But in your case, the only script that needs that can still be sourced, since you don't need $0 there.