Am experimenting a bit with trap on invalid command return code using a sample code #!/bin/bash# Exit on errortrap 'echo 'exiting..';exit' ERRset -eh=1b=$((h+)) # <----- command causing the errorecho $?echo $becho endAm not able to cause the trap to occur even though there is an offending instruction. But the same if I run in a sub-shell asfunction junk() {h=1b=$((h+))echo Exit code:$?echo $becho endecho Hello}junk(or) running the entire instructions in a sub-shell as(h=1b=$((h+))echo Exit code:$?echo $becho endecho Hello)am able to catch the command failure and the EXIT catches the trap and prints the message accordingly.Am aware of the usage of set -e -e  errexit When set, the shell exits when a simple command in a command list exits    non-zero (FALSE). This is not done in situations, where the exit code is already checked     (if, while, until, ||, &&)but I can't find a proper reference where it says happens only on a sub-shell or a function or something similar.Let me know if I am missing something basic here.
trap on command exit not working unless used in a function or sub-shell
bash;shell;signals;error handling;trap
What your are missing is that set -e and sigspec ERR both apply to command execution (commands that exit with a non-zero value). What you have here with b=$((h+)) is a parsing error. The command is not executed because it is not understood.Why does it work in a function or sub-shell? Because this parsing error makes the containing script (be it function or a sub-shell) fail as a whole. In other words, this is not b=$((h+)) that triggers your trap (there is no trap set in your sub-shells), this is the failure of the call to junk or to your subshell.