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
- I cannot use
return, because when I forget to source the script instead of calling it, return will not exit, and the rest of the script will be executed and mess things up. - I cannot use
exit, because this closes the shell. - I cannot use the nice trick
kill -SIGINT $$, because this doesn’t allow to return an exit code.
Is there any viable alternative that I have overlooked?
You can use
x"${BASH_SOURCE[0]}" == x"$0"to test if the script was sourced or called (false if sourced, true if called) andreturnorexitaccordingly.