加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

shell – “set -e”在一个函数中

发布时间:2020-12-15 18:45:26 所属栏目:安全 来源:网络整理
导读:set -e(或以#!/ bin / sh -e开头的脚本)对于自动弹出来是非常有用的,如果有问题.它可以节省我错误检查每个可能失败的命令. 如何在函数中获得相当于此的内容? 例如,我有以下脚本立即退出错误退出状态: #!/bin/sh -eecho "the following command could fail
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)

这可能是预期的行为.我的问题是:如何在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.

在你的情况下,虚假是管道之前的一部分!和if的一部分.所以解决方案是重写你的代码,使它不是.

换句话说,这里没有什么特别的功能.尝试:

set -e
! { false; echo hi; }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读