Am experimenting a bit with trap
on invalid command return code using a sample code
#!/bin/bash
# Exit on error
trap 'echo 'exiting..';exit' ERR
set -e
h=1
b=$((h+)) # <----- command causing the error
echo $?
echo $b
echo "end"
Am 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 as
function junk() {
h=1
b=$((h+))
echo "Exit code:$?"
echo $b
echo "end"
echo "Hello"
}
junk
(or) running the entire instructions in a sub-shell as
(h=1
b=$((h+))
echo "Exit code:$?"
echo $b
echo "end"
echo "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 'echo 'exiting..';exit' ERR
doesn't nest quotes, so you're popping out of quotes for the wordexiting...
and then back in again. I suspect that although this works it's not actually what you intend. I would suggest thattrap 'echo "exiting..";exit' ERR
might be better.