Skip to content
shellhacks.dev
Shell Scripting

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.

1 min read
Summarize in AI

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.

Shell
trap 'echo "cleanup ran"' 0
trap 'echo "HUP caught"' 1
trap
kill -HUP $$
echo "still running"
exit 3
Text
trap -- 'echo "cleanup ran"' EXIT
trap -- 'echo "HUP caught"' HUP
HUP caught
still running
cleanup ran

Condition 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.

Share

More snippets

Shell Scripting

Compare Dotted Version Numbers in POSIX sh

Compare dotted version numbers in POSIX sh by splitting on dots and comparing each field as an integer. Plain sort puts 1.10 before 1.9, and sort -V is a GNU option.

1 min read
Shell Scripting

Return Text from a Function in POSIX sh

A POSIX sh function returns text by printing it, and the caller captures the output with command substitution. Variables set inside are lost, and trailing newlines go.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.