On 8/6/22 14:44, Robert Elz wrote:
... bash allows a return in the trap string (not in a function called in that
string) if the
trap occurs while executing a function (then the return applies to that
function). ...
Yes! that is what I was missing. Years ago when I wrote my debugger, I
must have come across this and through trail and error I settled on
ending the DEBUG trap with 'setExitCode $action' (where .. setExitCode()
{ return $?; })
Even though I knew that bash did not push anything on the stack when it
called a trap script I always thought there must be some notion of
entering into and returning from a trap script but no, return in a trap
function is just like inserting a return in the interrupted script,
where ever its at!
Here is a test script that I just used to understand and confirm for
myself whats going on and that also illustrates the B behavior....
bash5.0.16$ cat bin/test.sh
#!/usr/bin/env bash
function setExitCode() { return $1; }
function f1() {
sleep 2
echo "f1 -- woke, no signal -- ending normally"
return 101
}
function childFn() {
trap 'echo "SIG: signal received -- ending f1 with last code 202 -> return
"; setExitCode 202; return ' SIGUSR1
trap 'echo "SIG: signal received -- ending f1 with last code 202 -> return
\$?"; setExitCode 202; return $?' SIGUSR2
f1
echo "f1 returned $?"
}
childFn &
child="$!"
sleep 1
case $1 in
1) echo "main: sending USR1"; kill -SIGUSR1 $child ;;
2) echo "main: sending USR2"; kill -SIGUSR2 $child ;;
*) echo "main: twiddling thumbs" ;;
esac
wait
echo
bash5.0.16$ bin/test.sh
main: twiddling thumbs
f1 -- woke, no signal -- ending normally
f1 returned 101
bash5.0.16$ bin/test.sh 1
main: sending USR1
SIG: signal received -- ending f1 with last code 202 -> return
f1 returned 0
bash5.0.16$ bin/test.sh 2
main: sending USR2
SIG: signal received -- ending f1 with last code 202 -> return $?
f1 returned 202
bash5.0.16$
The second run (that causes USR1 to interrupt f1) shows the B behavior
compared to the third (USR2) that shows the more correct A behavior by
explicitly using 'return $?'
--BobG