set -e
(或以#!/bin/sh -e
)对于出现问题时自动轰炸非常有用。它使我不必对每个可能失败的命令进行错误检查。
如何在函数内获得与此等效的内容?
例如,我有以下脚本,该脚本在出现错误时立即退出,并显示错误退出状态:
#!/bin/sh -e
echo "the following command could fail:"
false
echo "this is after the command that fails"
输出如预期:
the following command could fail:
现在我想将其包装到一个函数中:
#!/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
)
这大概是预期的行为。我的问题是:如何获得效果和用处set -e
在 shell 函数内?我希望能够进行一些设置,这样我就不必单独检查每个调用的错误,但脚本将在遇到错误时停止。它应该根据需要展开堆栈,直到我检查结果为止,或者如果我没有检查结果,则退出脚本本身。这是什么set -e
已经这样做了,只是它不嵌套。
我发现了同样的问题 http://www.unix.com/shell-programming-scripting/114716-strange-behaviour-set-e-functions.html在 Stack Overflow 外询问,但没有合适的答案。