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

Bash失败了快速功能

发布时间:2020-12-15 22:04:11 所属栏目:安全 来源:网络整理
导读:有建议使用以下选项使 Bash快速失败: set -o errexitset -o nounsetset -o pipefail 但是这些选项对于Bash函数没有预期的效果,通过管道传递||. 例如.在脚本中 #!/bin/bashset -o errexitset -o nounsetset -o pipefailmy_function() { test -z "$1" echo "t
有建议使用以下选项使 Bash快速失败:

set -o errexit
set -o nounset
set -o pipefail

但是这些选项对于Bash函数没有预期的效果,通过管道传递||.

例如.在脚本中

#!/bin/bash

set -o errexit
set -o nounset
set -o pipefail

my_function() {
    test -z "$1"
    echo "this SHOULD NOT be printed"
}

my_function 1 || echo "???" # 1

my_function 1 # 2

echo "this will not be printed"

第2行将导致脚本以代码1终止而没有任何输出.这就是我的期望.

线#1实际上让我困惑:my_function将成功完成,打印“不应该打印”并返回代码0,因此“???”将不会被打印.

我怎样才能让Bash在第1行处理my_function同样的快速失败方式,如第2行?

解决方法

还有更好的建议 not to use set -e/errexit

Clearly we don’t want to abort when the conditional (in if [ -d /foo ]; then),returns non-zero. […] The implementors decided to make a bunch of special rules,like “commands that are part of an if test are immune”,or “commands in a pipeline,other than the last one,are immune”.

These rules are extremely convoluted,and they still fail to catch even some remarkably simple cases. Even worse,the rules change from one Bash version to another,as Bash attempts to track the extremely slippery POSIX definition of this “feature”. When a SubShell is involved,it gets worse still — the behavior changes depending on whether Bash is invoked in POSIX mode.

如果脚本停止非零返回,则foo || bar也没用,因为bar永远不会运行(脚本会退出).因此,这些错综复杂的规则之一是在&&amp ;;的左侧命令中返回非零值.或||不会导致脚本退出.这就是你所看到的效果.

没有办法让set -e正常工作,没有自动替换.如果不编写手动错误处理,就无法按照自己的方式工作.

(编辑:李大同)

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

    推荐文章
      热点阅读