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