trap: trap signals on your script
If you want your script to ignore a kill signal (like Ctrl + C) or run a command before signal is executed, you can use ‘trap’ command.
You usually place
trap command at the beginning of the script:
trap COMMAND SIGNAL_SPEC
COMMANDcan be any command like
echo 'signal detected'. It will run when signal is detected (it does not ignore the signal). An empty string (
"") means to ignore the signal.
SIGNAL_SPECcan be a signal number (
15) o signal name (
SIGTERM). You can add several signals (separated by spaces).
trap -lto print a list of signal names and their corresponding numbers.
- To restore a signal to default value, just type
trap "" 2
- It ignores SIGINT signal (when you press Ctrl + C).
trap "echo 'SIGTSTP signal detected'" 20
- It runs echo command before triggering SIGTSTP signal (when you press Ctrl + Z).
trap "" 1 2 3 15
- It ignores several signals.
trap "" 2 # some code trap 2
trapcommand will restore SIGINT signal to its default value (it will not be ignored).