Exit a Script On Error
我正在构建一个shell脚本,它具有与此类似的
1 2 3 4 5 6 7 8 | 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指南。网址:http://tldp.org/ldp/abs/html/
在上下文中:
1 2 3 4 5 6 7 8 9 | 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 ... |
如果您希望能够处理错误而不是盲目退出,而不是使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #!/bin/bash f () { errcode=$? # 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 $errcode # 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 |
可以设置其他陷阱来处理其他信号,包括通常的unix信号加上其他bash伪信号
方法如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | #!/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 *** ************ ' |
你所需要的就是