Can a bash script distinguish between being called as a script and being run as a "source"?

Viewed 64

I have a bash script that has inside it:

exit 1

When I "source" this script instead of running it, it causes the caller to exit.

Is there a way that the script can determine that it's being run with "source" and not as its script?

1 Answers

You can use this check inside your script:

[[ $0 = $BASH_SOURCE ]] && echo "normal run" || echo "sourced run"

Or using if/else/fi wherever you're calling exit:

if [[ $0 = $BASH_SOURCE ]]; then
   exit 1
else
   # don't call exit
   echo "some error..."
fi
Related