2010-12-07 68 views
76

我建立一个shell脚本,有if功能像这样的:退出脚本上的错误

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 

... 

我希望脚本的执行显示错误消息后完成。我如何做到这一点?

回答

67

您是在寻找exit

这是最好的bash指南。 http://tldp.org/LDP/abs/html/

在背景:

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 

... 
+2

如果你喜欢的ABS,你一定会喜欢的[BashGuide(http://mywiki.wooledge.org/BashGuide),[BashFAQ]( http://mywiki.wooledge.org/BashFAQ)和[BashPitfalls](http://mywiki.wooledge.org/BashPitfalls)。 – 2010-12-08 04:45:12

-5

exit 1是你所需要的。 1是一个返回码,所以如果你想要的话,你可以改变它,比如1意味着成功运行,而-1意味着失败或类似的东西。

+12

在unix中,成功始终是0.这可能有助于使用`test`或`&&`或`||`。 – mouviciel 2010-12-07 21:27:35

+4

要扩展mouviciel的评论:在shell脚本中,0总是意味着成功,1到255意味着失败。 -1超出范围(并且通常与255有相同的效果,所以失败如1)。 – Gilles 2010-12-07 22:14:17

+0

@mouviciel,@Gilles:感谢您的额外信息。自从我处理bash以来已经有一段时间了。 – DGH 2010-12-08 01:37:01

252

如果您将set -e放在脚本中,脚本中的任何命令都会失败(即任何命令返回非零值状态),脚本将立即终止。这不会让你编写自己的消息,但通常失败的命令自己的消息就足够了。

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

命令其地位是通过条件(如if&&||)测试不终止脚本(否则有条件的将是毫无意义)。偶然的命令失败并不重要的习惯用法是command-that-may-fail || true。您还可以通过set +e关闭部分脚本set -e

33

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

#!/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信号加上其它击伪信号RETURNDEBUG

5

下面是做到这一点的方式:

#!/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 *** 
************ 
'