Use Signal Numbers with trap in POSIX sh Scripts
In POSIX sh, trap accepts 0 for exit and a short list of signal numbers. Use names in new scripts and numbers only where an older shell needs them.
A script must clean up when it exits and react to a hangup, and it has to run under shells that disagree about signal names.
trap 'echo "cleanup ran"' 0
trap 'echo "HUP caught"' 1
trap
kill -HUP $$
echo "still running"
exit 3trap -- 'echo "cleanup ran"' EXIT
trap -- 'echo "HUP caught"' HUP
HUP caught
still running
cleanup ranCondition 0 means the shell is exiting and every POSIX shell accepts it, while the name EXIT came later. POSIX also fixes a few numbers: 1 for HUP, 2 for INT, 3 for QUIT, 6 for ABRT, 9 for KILL, 14 for ALRM and 15 for TERM. The run in dash listed the traps, ran the HUP handler when the script sent itself the signal, kept going, and then ran the exit handler after exit 3. See trap in the specification.
Any number outside that list is implementation-defined, so signal 10 or 12 means different things on Linux and the BSDs, and a name such as USR1 is safer. KILL and STOP cannot be trapped at all, and the exit handler does not run when the shell is killed with SIGKILL.