错误退出脚本

问题描述 投票:125回答:5

我正在构建具有if这样的功能的Shell脚本:

if jarsigner -verbose -keystore $keyst -keystore $pass $jar_file $kalias
then
    echo $jar_file signed sucessfully
else
    echo ERROR: Failed to sign $jar_file. Please recheck the variables
fi

...

我希望在显示错误消息后完成脚本的执行。我该怎么做?

bash exit shell
5个回答
120
投票
您是否正在寻找exit

这是最好的bash指南。exit

在上下文中:

http://tldp.org/LDP/abs/html/


320
投票
如果将

if jarsigner -verbose -keystore $keyst -keystore $pass $jar_file $kalias then echo $jar_file signed sucessfully else echo ERROR: Failed to sign $jar_file. Please recheck the variables 1>&2 exit 1 # terminate and indicate error fi ... 放在脚本中,则脚本将在脚本中的任何命令失败时终止(即,任何命令返回非零状态时)。这不能让您编写自己的消息,但是失败命令自己的消息通常就足够了。

这种方法的优点是它是自动的:您不会冒忘记处理错误情况的风险。

其状态由条件(例如set -eif&&)测试的命令不会终止脚本(否则该条件将毫无意义)。对于偶然的命令而言,失败无关紧要的成语是||。您也可以使用command-that-may-fail || true关闭脚本的一部分的set -e


40
投票
如果您希望能够处理错误而不是盲目退出,而不是使用set +e,请在set -e伪信号上使用trap

ERR

可以将其他陷阱设置为处理其他信号,包括通常的Unix信号以及其他Bash伪信号#!/bin/bash
f () {
    errorCode=$? # save the exit code as the first thing done in the trap function
    echo "error $errorCode"
    echo "the command executing at the time of the error was"
    echo "$BASH_COMMAND"
    echo "on line ${BASH_LINENO[0]}"
    # do some error handling, cleanup, logging, notification
    # $BASH_COMMAND contains the command that was being executed at the time of the trap
    # ${BASH_LINENO[0]} contains the line number in the script of that command
    # exit the script or return to try again, etc.
    exit $errorCode  # or use some other value or do return instead
}
trap f ERR
# do some stuff
false # returns 1 so it triggers the trap
# maybe do some other stuff
RETURN

8
投票
这里是这样做的方法:

DEBUG


-8
投票
#!/bin/sh abort() { echo >&2 ' *************** *** ABORTED *** *************** ' echo "An error occurred. Exiting..." >&2 exit 1 } trap 'abort' 0 set -e # Add your script below.... # If an error occurs, the abort() function will be called. #---------------------------------------------------------- # ===> Your script goes here # Done! trap : 0 echo >&2 ' ************ *** DONE *** ************ ' 是您所需要的。 exit 1是一个返回码,因此,如果您想将1表示成功运行,而将1表示失败或类似情况,则可以更改它。
© www.soinside.com 2019 - 2024. All rights reserved.