问题
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?
回答1:
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.
回答2:
Use this instead of exit or return:
[ $PS1 ] && return || exit;
Works whether sourced or not.
回答3:
The answer to the question title (not in the body as other answers have addressed) is:
Return an exit code without closing shell
(exit 33)
That sets the exit code without exiting the shell (nor a sourced script).
For the more complex question of exiting (with an specific exit code) either if executed or sourced:
#!/bin/bash
[ "$BASH_SOURCE" == "$0" ] &&
echo "This file is meant to be sourced, not executed" &&
exit 30
return 88
Will set an exit code of 30 (with an error message) if executed.
And an exit code of 88 if sourced.
Will exit both the execution or the sourcing without affecting the calling shell.
回答4:
Another option is to use a function and put the return values in that and then simply either source the script (source processStatus.sh) or call the script (./processStatus.sh) . For example consider the processStatus.sh script that needs to return a value to the stopProcess.sh script but also needs to be called separately from say the command line without using source (only relevant parts included) Eg:
function checkProcess {
if [ $1 -eq "50" ]
then
return 1
else
return 0
fi
}
checkProcess
and
source processStatus.sh $1
RET_VALUE=$?
if [ $RET_VALUE -ne "0" ]
then
exit 0
fi
来源:https://stackoverflow.com/questions/6112540/return-an-exit-code-without-closing-shell