Not sure why the $? and $! values in the foo function don't pertain to the CHLD in question, but the following fixes seem to get around the problem, by using jobs -p inside the foo function, like so:
#!/usr/bin/env bash
set -m # allow for job control
EXIT_CODE=0 # exit code of overall script
function foo() {
for job in `jobs -p`; do
echo "PID => ${job}"
if ! wait ${job} ; then
echo "At least one test failed with exit code => $?" ;
EXIT_CODE=1;
fi
done
}
trap 'foo' CHLD
DIRN=$(dirname "$0")
commands=(
"{ echo "foo"'foo' && exit 4; }"
"{ echo "bar"'bar' && exit 3; }"
"{ echo "baz"'baz' && exit 5; }"
)
clen=`expr "${#commands[@]}" - 1` # get length of commands - 1
for i in `seq 0 "$clen"`; do
(echo "${commands[$i]}" | bash) & # run the command via bash in subshell
echo "$i ith command has been issued as a background job"
done
wait # wait for all to finish
echo "EXIT_CODE => $EXIT_CODE"
exit "$EXIT_CODE"