Shell - Using Trap to Catch and Handle Signals

trap command is a function of the shell to handle signals.

Basic examples:

example
1
2
3
4
5
6
trap arg signal_spec ... # signal_spec can be either SIGINT like string or a number for that signal, the "SIG" is not required
trap 'echo "Ctrl-C captured"' INT # when pressing Ctrl-C, echo the string and continue running
trap 'echo "Ctrl-C captured"; exit' INT # when pressing Ctrl-C, echo the string and exit
trap '' INT # ignroe INT signal, proceed even when you press Ctrl-C
trap INT # reset handlers for INT signal
trap '-' INT # reset handlers for INT signal