-1

Is there a bash command like source except it will only source a file once for a given shell?

for example:

source_cached foo.sh    # runs as normal
source_cached foo.sh    # would not load foo.sh a second time

since the foo.sh path has already been sourced, it would not source it again.

0

1 Answer 1

1

What you want is called an "include guard". You can see an example on SO by Jonathan Leffler at https://stackoverflow.com/a/7518684/6512983.

if [ -z "$B_SH_INCLUDED" ]
then
    B_SH_INCLUDED=yes
    ...rest of original contents of b.sh
fi

Essentially you define a variable in the file you've included, but check for its existence beforehand and return prematurely if it's already defined.

Not the answer you're looking for? Browse other questions tagged .