出错时退出脚本
我正在构建一个具有 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
...
我希望在显示错误消息后完成脚本的执行。我怎样才能做到这一点?
I'm building a Shell Script that has a if
function like this one:
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
...
I want the execution of the script to finish after displaying the error message. How I can do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果将
set -e
放入脚本中,一旦其中的任何命令失败(即任何命令返回非零状态),脚本就会终止。这不允许您编写自己的消息,但通常失败命令自己的消息就足够了。这种方法的优点是它是自动的:您不会冒忘记处理错误情况的风险。
通过条件(例如
if
、&&
或||
)测试其状态的命令不会终止脚本(否则有条件的就毫无意义)。对于偶尔失败无关紧要的命令,有一个习语:command-that-may-fail ||正确。您还可以使用set +e
关闭脚本部分的set -e
。If you put
set -e
in a script, the script will terminate as soon as any command inside it fails (i.e. as soon as any command returns a nonzero status). This doesn't let you write your own message, but often the failing command's own messages are enough.The advantage of this approach is that it's automatic: you don't run the risk of forgetting to deal with an error case.
Commands whose status is tested by a conditional (such as
if
,&&
or||
) do not terminate the script (otherwise the conditional would be pointless). An idiom for the occasional command whose failure doesn't matter iscommand-that-may-fail || true
. You can also turnset -e
off for a part of the script withset +e
.您是否正在寻找
退出
?这是最好的 bash 指南。
http://tldp.org/LDP/abs/html/
在上下文中:
Are you looking for
exit
?This is the best bash guide around.
http://tldp.org/LDP/abs/html/
In context:
如果您希望能够处理错误而不是盲目退出,请在
ERR
伪值上使用trap
,而不是使用set -e
信号。可以设置其他陷阱来处理其他信号,包括常见的 Unix 信号以及其他 Bash 伪信号
RETURN
和DEBUG
。If you want to be able to handle an error instead of blindly exiting, instead of using
set -e
, use atrap
on theERR
pseudo signal.Other traps can be set to handle other signals, including the usual Unix signals plus the other Bash pseudo signals
RETURN
andDEBUG
.方法如下:
Here is the way to do it: