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.
  • 46,058
  • 19
  • 106
  • 116
vy32
  • 28,461
  • 37
  • 122
  • 246
  • 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
  • 761,203
  • 64
  • 569
  • 643