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)
解决方法
-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陷阱的类似错误类别.然而,这种解释纯属猜测.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。