gpt4 book ai didi

shell - 如何在shell函数中获得 "set -e"的效果和用处?

转载 作者:行者123 更新时间:2023-12-03 08:48:06 24 4
gpt4 key购买 nike

set -e (或以 #!/bin/sh -e 开头的脚本)对于在出现问题时自动轰炸非常有用。它使我不必对每个可能失败的命令进行错误检查。

如何在函数中获得与 this 等效的值?

例如,我有以下脚本,该脚本在出现错误时立即退出并显示错误退出状态:

#!/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已经,除了它不嵌套。

我找到了 the same question在 Stack Overflow 之外询问但没有合适的答案。

最佳答案

来自 set -e 的文档:

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, or if keyword, and is not a part of an AND or OR list, and is not a pipeline preceded by the ! reserved word, then the shell shall immediately exit.



在您的情况下, false是以 ! 开头的管道的一部分和 if 的一部分.因此,解决方案是重写您的代码,使其不是。

换句话说,这里的函数没有什么特别之处。尝试:
set -e
! { false; echo hi; }

关于shell - 如何在shell函数中获得 "set -e"的效果和用处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4072984/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com