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

bash – 设置只读变量时不调用ERR陷阱

发布时间:2020-12-15 22:55:09 所属栏目:安全 来源:网络整理
导读:脚本test.sh: set -euo pipefailfunction _trap_ext{ echo '_trap_ext'}function _trap_error{ echo '_trap_error'}trap "_trap_ext" EXITtrap "_trap_error" ERRreadonly foo='bar'foo='bar'echo 'foobar' 输出: ./test.sh: line 14: foo: readonly varia
脚本test.sh:

set -euo pipefail

function _trap_ext
{
    echo '_trap_ext'
}
function _trap_error
{
    echo '_trap_error'
}
trap "_trap_ext" EXIT
trap "_trap_error" ERR

readonly foo='bar'
foo='bar'

echo 'foobar'

输出:

./test.sh: line 14: foo: readonly variable
_trap_ext

由于错误(-e选项),脚本终止于第14行,但未调用_trap_error函数.为什么不?

GNU bash,版本4.1.2(1)-release(x86_64-unknown-linux-gnu),4.2.45(1)-release(i586-suse-linux-gnu)

解决方法

这听起来像是一个bug.从手册页:

-e
Exit immediately if a pipeline (which may consist of a single simple command),a list,or a compound command (see SHELL above),exits with a non-zero status.

A trap on ERR,if set,is executed before the shell exits. This option applies to the shell environment and each subshell environment separately (see COMMAND ENVIRONMENT above),and may cause subshells to exit before executing all the commands in the subshell.

从手册页中可以看出,它应该执行ERR陷阱.您可以通过在foo =’bar’语句之前插入false来测试它是否在其他情况下按预期工作.

似乎bash也没有在语法错误上调用ERR陷阱,因此尝试覆盖只读变量可能属于跳过ERR陷阱的类似错误类别.然而,这种解释纯属猜测.

(编辑:李大同)

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

    推荐文章
      热点阅读