![](/img/trans.png)
[英]Can I create a bash script that relies on the exit code from the previously executed command in my shell?
[英]In a bash script that starts with set -e, can I set the exit code to a different value than the first failed command's?
我目前正在研究一些应该使用set -e
并确认Linux Standard Base核心规范的init脚本。 现在这两个人并没有真正合作:
由于set -e
,第一个失败的命令导致脚本以失败命令的返回值退出,因此无法将脚本的退出状态设置为符合LSB符合LSB不兼容返回值失败的命令。 我可以在每个这样的命令之前unset -e
,但这很麻烦,在这种情况下,我实际上根本不使用set -e
?
我想另一种方法来实现与unset -e
相同的结果将是做类似的事情
returns_1() { return 1; }
...
cmd_that_fails_with_non_LSB_return_values || returns_1
但这似乎也很笨重,我再次必须检查每个命令的可能返回值。
是否有一种方法可以设置脚本在终止时由于set -e
为固定值而返回的错误代码,因此它将返回1(即LSB一般/未指定的错误),而不管失败命令的返回值是多少? 我不应该打扰LSB符合返回码和/或设置-e吗? (这可能会变成关于set -e
的优点的讨论,无论如何从你获得的搜索结果量来判断)
小代码片段来说明问题:
#!/bin/bash
# init script for service foo
set -e
start() {
echo "bar"
cmd_fails_with_return_code_3 # script exits with return code 3, not LSB conformant
echo "baz"
}
...
case "$1" in
start)
start
;;
...
esac
在手册页中,您可以在ERR
上设置陷阱:
A trap on ERR, if set, is executed before the shell exits.
我没试过这个,但这意味着这样的事可能对你有所帮助:
trap "exit 1" ERR
请务必阅读手册页以获取其他有用选项,例如-E
以继承子shell中的ERR陷阱。
虽然returns
函数是多余的,但你基本上已经将其固定。
cmd_that_fails_with_non_LSB_return_values || exit 1
更典型的是,如果只是为了报告发生的事情,你实际上会以某种方式处理错误。
die () {
echo "$0: $@" >&2
exit 1
}
:
cmd_that_fails_with_non_LSB_return_values ||
die "Long command with underscores failed; aborting"
从哲学上讲,我认为set -e
的目的主要是“温和地提醒”(即强制)你处理所有可能的错误条件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.