That trap call is creating an interesting recursion, because $BASH_COMMAND
(and $?
) are being expanded when the trap
command executes. However, $BASH_COMMAND
at that point is the trap command itself, textually including $BASH_COMMAND
(and some quotes and semicolons). Actually figuring out what the command to be executed when the trap fires is an interesting study, but it's not necessary to fix the problem, which you can do like this:
trap '{ echo "$BASH_COMMAND failed with status code $?"; handle_error; }' ERR
Note that replacing "
with '
not only avoids immediate parameter expansion, it also avoids have to escape the inner "
s.