我正在使用“set -e”使脚本在出错时退出,但如果我在函数内部出错,我不希望它退出,我希望函数返回错误< / p>
例如:
#!/bin/bash
set -e
func() {
echo 1
# code ...
cause_error
echo This should not print
}
func
if [ $? -ne 0 ]; then
echo I want this print
else
echo This should not print either
fi
此脚本的输出为:
$ /tmp/test.sh
1
但我希望如此:
1
I want this print
这可能吗?或者我是否必须测试函数内执行的每个命令的退出状态?
答案 0 :(得分:0)
你可以这样做:
A
答案 1 :(得分:0)
您要求的行为是不可能的。您希望函数在出错时返回,并且脚本不退出,即使使用set -e
选项也是如此。你要求bash解释器的要求是检查每一行的退出状态,如果它在函数内,则返回非零代码,否则退出。
您无法满足您的要求。但您可以选择禁用set -e
来执行该功能。禁用set -e
的方法是使用set +e
选项或使用&& :
技巧
以下是使用&& :
技巧
#!/bin/bash
set -e
func() {
echo 1
# code ...
return 1
echo This should not print
}
func && :
if [ $? -ne 0 ]; then
echo I want this print
else
echo This should not print either
fi
输出:
1
I want this print
答案 2 :(得分:0)
明确比较$?
是一个反模式,但另外,摆脱它也会绕过set -e
,因为当条件发生故障时它不会失败。
无论set -e
如何,您正在尝试执行的操作的正确语法是
if func; then
echo I want this print
else
echo This should not print either
fi
函数中的失败将导致函数报告错误,就像您在散文描述中所说的那样,但这也意味着条件将打印This should not print either
。如果您不想这样,可以编辑您的问题以澄清这个自相矛盾的要求。