I am confused about the processing of SIGINT and EXIT traps in Bash scripts.
I wrote this script to test:
#!/usr/bin/env bash
set -e
exit_trap() {
printf "In exit_trap \$?=$?\n"
exit 0
}
sigint_trap() {
printf "In sigint_trap \$?=$?\n"
exit 1
}
trap exit_trap EXIT
trap sigint_trap SIGINT
sleep 1d
If I execute it as is, and interrupt with Ctrl-C, I get exit code 0
and this printout:
^CIn sigint_trap $?=130
In exit_trap $?=1
If I comment out the trap sigint_trap SIGINT
line, I get exit code 130
and this printout:
^CIn exit_trap $?=0
(Note the extra blank line, by the way.)
I do not understand the order of execution and the exit code propagation. In particular, why does exit 0
in the EXIT
trap not produce 0
exit code without the SIGINT
trap?
Can anyone explain, please?
sleep
and there is no trap for SIGINT in the shell, the shell kills itself with SIGINT at the very end because of WCE; in effectexit 0
does not matter. I'm not sure why we getIn exit_trap $?=0
though. Waiting for a good answer.In exit_trap $?=0
seems to be the exit status of thetrap exit_trap EXIT
command itself ... Shell seems to die after SIGINT leaving out some unfinished tasks like updating$?
with the last status ... Send SIGQUIT instead with Ctrl+\\ and that should terminate differently ... Trapping SIGINT intercepts it so the shell terminates differently byexit 1
in your function and not because of SIGINT.