A trap invoked in a function called from inside of loop is not invoked. A trap works as expected if invoked in loop body directly. Same function, if called outside of loop, invokes trap.
#!/bin/bash
function error_handler() #---------------------
{
echo "ERROR STATUS: $?"
echo "ERROR COMMAND: $BASH_COMMAND"
echo "ERROR STACK:"
caller
echo "---------- end of stack dump ----------"
exit 1
}
function func()
{
echo "..inside func( $1)"
if false
then
true
rv=0
else
false
rv=1
fi
echo "..returning from func( $1), rv=$rv"
return $rv
}
set -o errtrace -o errexit
trap error_handler ERR
for N in 1 2 ; do
echo -e "\nbegin loop $N"
if func $N
then
echo "result of func($N): success"
else
echo "result of func($N): failed"
fi
echo "loop $N is done"
false
done
func 1
func 2
Actual result running script above:
begin loop 1
..inside func( 1)
..returning from func( 1), rv=1
result of func(1): failed
loop 1 is done
ERROR STATUS: 1
ERROR COMMAND: false
ERROR STACK:
41 ./a.sh
---------- end of stack dump ----------
but I expect trap from the false
line inside func()
, not the false
at the end of the program.
Let's comment out false
at the end. Result is:
begin loop 1
..inside func( 1)
..returning from func( 1), rv=1
result of func(1): failed
loop 1 is done
begin loop 2
..inside func( 2)
..returning from func( 2), rv=1
result of func(2): failed
loop 2 is done
..inside func( 1)
ERROR STATUS: 1
ERROR COMMAND: false
ERROR STACK:
21 ./a.sh
---------- end of stack dump ----------
A trap was invoked inside func()
now, but not in loop 1! Both loop 1 and loop 2 are completed without trap. It was func 1
after the function returns, which invoked a trap. Too late.
Why?