bashreturnexitreturn-code

Return an exit code without closing shell


I'd like to return an exit code from a BASH script that is called within another script, but could also be called directly. It roughly looks like this:

#!/bin/bash
dq2-get $1
if [ $? -ne 0 ]; then
  echo "ERROR: ..."
  # EXIT HERE
fi
# extract, do some stuff
# ...

Now in the line EXIT HERE the script should exit and return exit code 1. The problem is that

Is there any viable alternative that I have overlooked?


Solution

  • You can use x"${BASH_SOURCE[0]}" == x"$0" to test if the script was sourced or called (false if sourced, true if called) and return or exit accordingly.