3

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?

Benjamin W.
  • 38,596
  • 16
  • 96
  • 104
vy32
  • 26,286
  • 33
  • 110
  • 218
  • See [BashFAQ/109 (How can I tell whether my script was sourced (dotted in) or executed?)](https://mywiki.wooledge.org/BashFAQ/109) – pjh Oct 21 '19 at 18:17

1 Answers1

6

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
anubhava
  • 713,503
  • 59
  • 514
  • 593