Signal Handling

The shell can receive signals just like any other process. The trap utility can be used to,

  • Register a signal action (signal handler)

  • Ignore a signal

  • Reset a signal disposition to the default action

In addition to signal handling, the trap utility also allows a signal action to be registered to execute on exit.

There are some specific rules about which signals can be ignored, reset, and handled by the shell, and how signal handling works in subshells, outlined in TRAP(1P).

Signal handling can be used to catch signals that might otherwise cause the shell to terminate. Additionally, trapping on EXIT is frequently used to clean up temporary files created by a shell script, in case it exits through an unintended control path.

$ printf 'trap "echo goodbye!" EXIT\n' > script.sh
$ sh script.sh
goodbye!