ERR trap not called when setting readonly variable

Script 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' 

Output:

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

The script terminates at line 14 due to an error ( -e ), but the _trap_error function _trap_error not called. Why not?

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

+6
source share
1 answer

It seems like it could be a mistake. From the man pages:

-e
Exit immediately if the pipeline (which may consist of a simple simple command), a list, or a compound command (see SHELL above) terminates with a non-zero status.
...
The ERR trap, if installed, runs before the shell exits. This parameter applies to the shell environment and each subnet environment separately (see the "GENERAL ENVIRONMENT" section above) and can call subshells to exit before all the commands in the subshell are executed.

From what a person’s pages say, he must execute the ERR trap. You can verify that it works as expected in other situations by inserting false before the foo='bar' statement.

It is also found that bash does not cause an ERR trap for syntax errors, so it may be that trying to overwrite the readonly variable falls into a similar category of errors that skip the ERR trap. However, this explanation is pure speculation.

+1
source

Source: https://habr.com/ru/post/984441/


All Articles