Use trap in Bash to trap signals

Update 2017-09-96: add example to use the name of the signals. Thanks to Thomas and Lokta.

Bash can intercept signals send by some special keys like Ctrl-C and change their default behaviour. In order to do that, you must use the trap command. This command take as argument the command you want to execute when the signal is emitted and the list of signals you want to trap.

For instance:

trap "echo yollo" 2 3

will print yollo when Ctrl-C is pressed.

To get the list of all signals, with their numbers and their names, you can use kill.

kill -l
1) SIGHUP       2) SIGINT       3) SIGQUIT      4) SIGILL
5) SIGTRAP      6) SIGABRT      7) SIGEMT       8) SIGFPE
9)SIGKILL     10) SIGBUS      11) SIGSEGV     12) SIGSYS

To use the names of the signal instead, use:

trap "echo 'sig INT caught' " INT

You can also use it to kill the children of a process with:

trap "trap - SIGTERM && kill -- -$$" SIGINT SIGTERM EXIT