I have this bash script:
#!/usr/bin/env bash
set -m # allow for job control
EXIT_CODE=0 # exit code of overall script
function foo() {
echo "CHLD pid is $!" # doesn't seem to be the expected pid
echo "CHLD exit code is $?" #exit code seems to pertain to some other process
if [[ $? > 0 ]]; then
echo "at least one test failed"
EXIT_CODE=1
fi
}
trap 'foo' CHLD
DIRN=$(dirname "$0")
commands=(
"echo 'foo'; exit 1;"
"echo 'bar'; exit 0;"
"echo 'baz'; exit 2;"
)
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 for all to finish
wait
echo "EXIT_CODE => $EXIT_CODE"
exit "$EXIT_CODE"
Multiple subshells exit, and fire the foo function upon exit. I would have only expected 3 CHLD events captured by the foo function, but there are at least 6.
How can I discriminate between the CHLD events that appear in the foo function?
For example, here is the output of the above script:
CHLD exit code is 0
CHLD exit code is 0
CHLD exit code is 0
0 ith command has been issued as a background job
1 ith command has been issued as a background job
2 ith command has been issued as a background job
bar
baz
foo
CHLD exit code is 0
CHLD exit code is 0
CHLD exit code is 0
EXIT_CODE => 0
As you can see, there are 6 CHLD events; but I really only care about 3. Furthermore, I should be seeing 1,0,2 as exit codes, not 0,0,0.
So I have two questions:
- Is there a way to id which subshell is exiting in the foo function?
- Why am I seeing 0 for the exit code, when it should be 1, or 2?
$(dirname ...),`expr ...`,`seq ...`, and I don't think$!will contain the exit status of backgrounded processes.echo.