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.
Usage
You usually place trap
command at the beginning of the script:
trap COMMAND SIGNAL_SPEC
COMMAND
can be any command likeecho 'signal detected'
. It will run when signal is detected (it does not ignore the signal). An empty string (""
) means to ignore the signal.SIGNAL_SPEC
can be a signal number (15
) o signal name (SIGTERM
). You can add several signals (separated by spaces).- Type
trap -l
to print a list of signal names and their corresponding numbers. - To restore a signal to default value, just type
trap
andSIGNAL_SPEC
.
Examples
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
- Second
trap
command will restore SIGINT signal to its default value (it will not be ignored).
If you have any suggestion, feel free to contact me via social media or email.
Latest tutorials and articles:
Featured content: