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

脚本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陷阱的类似错误类别.然而,这种解释纯属猜测.

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...