Trapping Signals

Signal trapping is another technique to make your script close gracefully. There are situations where you want to perform some cleanup steps regardless of exit signals, including the infamous CTRL + C cancel process interrupt. Hence, we use trap.

Trapping Example

To trap the signal, we use the keyword trap and signal keyword like exit. Then, we write an exit_trap function to wrap around your clean up codes. Here's an example:

#!/bin/sh

# do something dangerously

exit_trap() {
        # handle exit gracefully
}
trap exit_trap INT QUIT TERM EXIT

Caution

Since we're trapping all sort of exit signal, you need to write your cleanup codes taking all the possible cases. You can identify them individually using the signal table, available at:

  1. http://pubs.opengroup.org/onlinepubs/007904975/utilities/trap.html
  2. http://pubs.opengroup.org/onlinepubs/007904975/basedefs/signal.h.html

The difference is that there is no SIG prefix. Example: SIGINT signal is INT instead. There are other cool signals like:

  • EXIT - terminal exit signal
  • INT - terminal interrupt signal
  • QUIT - terminal quit signal
  • TERM - termination signal
  • HUP - hangup

That's all about trapping signals and graceful exit.