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:
- http://pubs.opengroup.org/onlinepubs/007904975/utilities/trap.html
- 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 signalINT
- terminal interrupt signalQUIT
- terminal quit signalTERM
- termination signalHUP
- hangup
That's all about trapping signals and graceful exit.