Exit Shell Script Based on Process Exit Code

2019-01-03 19:24发布

I have a shell script that executes a number of commands. How do I make the shell script exit if any of the commands exit with a non-zero exit code?

标签: bash shell
9条回答
ゆ 、 Hurt°
2楼-- · 2019-01-03 19:52
#
#------------------------------------------------------------------------------
# run a command on failure exit with message
# doPrintHelp: doRunCmdOrExit "$cmd"
# call by:
# set -e ; doRunCmdOrExit "$cmd" ; set +e
#------------------------------------------------------------------------------
doRunCmdOrExit(){
    cmd="$@" ;

    doLog "DEBUG running cmd or exit: \"$cmd\""
    msg=$($cmd 2>&1)
    export exit_code=$?

    # if occured during the execution exit with error
    error_msg="Failed to run the command:
        \"$cmd\" with the output:
        \"$msg\" !!!"

    if [ $exit_code -ne 0 ] ; then
        doLog "ERROR $msg"
        doLog "FATAL $msg"
        doExit "$exit_code" "$error_msg"
    else
        #if no errors occured just log the message
        doLog "DEBUG : cmdoutput : \"$msg\""
        doLog "INFO  $msg"
    fi

}
#eof func doRunCmdOrExit
查看更多
我想做一个坏孩纸
3楼-- · 2019-01-03 19:56

If you want to work with $?, you'll need to check it after each command, since $? is updated after each command exits. This means that if you execute a pipeline, you'll only get the exit code of the last process in the pipeline.

Another approach is to do this:

set -e
set -o pipefail

If you put this at the top of the shell script, it looks like bash will take care of this for you. As a previous poster noted, "set -e" will cause bash to exit with an error on any simple command. "set -o pipefail" will cause bash to exit with an error on any command in a pipeline as well.

See here or here for a little more discussion on this problem. Here is the bash manual section on the set builtin.

查看更多
一纸荒年 Trace。
4楼-- · 2019-01-03 20:00

If you just call exit in the bash with no parameters, it will return the exit code of the last command. Combined with OR the bash should only invoke exit, if the previous command fails. But I haven't tested this.

command1 || exit;
command2 || exit;

The Bash will also store the exit code of the last command in the variable $?.

查看更多
登录 后发表回答