退出脚本上的错误
问题描述:
我建立一个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
...
我希望脚本的执行显示错误消息后完成。我如何做到这一点?
答
您是在寻找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
...
答
exit 1
是你所需要的。 1
是一个返回码,所以如果你想要的话,你可以改变它,比如1
意味着成功运行,而-1
意味着失败或类似的东西。
答
如果您将set -e
放在脚本中,脚本中的任何命令都会失败(即任何命令返回非零值状态),脚本将立即终止。这不会让你编写自己的消息,但通常失败的命令自己的消息就足够了。
这种方法的优点是它是自动的:您不会冒着忘记处理错误情况的风险。
命令其地位是通过条件(如if
,&&
或||
)测试不终止脚本(否则有条件的将是毫无意义)。偶然的命令失败并不重要的习惯用法是command-that-may-fail || true
。您还可以通过set +e
关闭部分脚本set -e
。
答
如果您希望能够处理错误而不是盲目退出,而不是使用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信号加上其它击伪信号RETURN
和DEBUG
。
答
下面是做到这一点的方式:
#!/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 ***
************
'
如果你喜欢的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