4

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?

2
  • 4
    "I get exit code 130" – Probably related to WCE (see e.g. this answer and links therein). I guess when Ctrl-C kills 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 effect exit 0 does not matter. I'm not sure why we get In exit_trap $?=0 though. Waiting for a good answer. Commented Sep 28 at 21:14
  • In exit_trap $?=0 seems to be the exit status of the trap 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 by exit 1 in your function and not because of SIGINT. Commented Sep 30 at 15:11

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.