如何获得“set -e"的效果和用处?在shell函数中? [英] How do I get the effect and usefulness of "set -e" inside a shell function?
问题描述
set -e
(或以 #!/bin/sh -e
开头的脚本)对于在出现问题时自动轰炸非常有用.它使我不必对每个可能失败的命令进行错误检查.
set -e
(or a script starting with #!/bin/sh -e
) is extremely useful to automatically bomb out if there is a problem. It saves me having to error check every single command that might fail.
如何在函数中获得与 this 等效的值?
How do I get the equivalent of this inside a function?
例如,我有以下脚本,该脚本在出错时立即退出并显示错误退出状态:
For example, I have the following script that exits immediately on error with an error exit status:
#!/bin/sh -e
echo "the following command could fail:"
false
echo "this is after the command that fails"
输出符合预期:
the following command could fail:
现在我想把它包装成一个函数:
Now I'd like to wrap this into a function:
#!/bin/sh -e
my_function() {
echo "the following command could fail:"
false
echo "this is after the command that fails"
}
if ! my_function; then
echo "dealing with the problem"
fi
echo "run this all the time regardless of the success of my_function"
预期输出:
the following command could fail:
dealing with the problem
run this all the time regardless of the success of my_function
实际输出:
the following output could fail:
this is after the command that fails
run this all the time regardless of the success of my_function
(即函数忽略了 set -e
)
这大概是预期的行为.我的问题是:如何在 shell 函数中获得 set -e
的效果和用处?我希望能够设置一些东西,这样我就不必单独检查每个调用的错误,但是脚本会在遇到错误时停止.它应该尽可能地展开堆栈,直到我检查结果,或者如果我没有检查它就退出脚本本身.这是 set -e
已经做的,除了它不嵌套.
This presumably is expected behaviour. My question is: how do I get the effect and usefulness of set -e
inside a shell function? I'd like to be able to set something up such that I don't have to individually error check every call, but the script will stop on encountering an error. It should unwind the stack as far as is needed until I do check the result, or exit the script itself if I haven't checked it. This is what set -e
does already, except it doesn't nest.
我发现 相同在 Stack Overflow 之外提出的问题,但没有合适的答案.
I've found the same question asked outside Stack Overflow but no suitable answer.
推荐答案
来自 set -e
的文档:
当这个选项打开时,如果一个简单的命令对于任何一个后果中列出的原因Shell 错误或返回退出状态值 > 0,并且不属于while
后面的复合列表,until
或 if
关键字,并且不是AND
或 OR
列表的一部分,并且不是以 !
保留的管道字,那么壳应立即退出.
When this option is on, if a simple command fails for any of the reasons listed in Consequences of Shell Errors or returns an exit status value > 0, and is not part of the compound list following a
while
,until
, orif
keyword, and is not a part of anAND
orOR
list, and is not a pipeline preceded by the!
reserved word, then the shell shall immediately exit.
在您的情况下,false
是 !
和 前面的管道的一部分 if
.因此,解决方案是重写您的代码,使其不是.
In your case, false
is a part of a pipeline preceded by !
and a part of if
. So the solution is to rewrite your code so that it isn't.
换句话说,这里的函数没有什么特别之处.试试:
In other words, there's nothing special about functions here. Try:
set -e
! { false; echo hi; }
这篇关于如何获得“set -e"的效果和用处?在shell函数中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!