Handling signals from within Bash has a simple syntax and can be used to handle user interruption with Ctrl-C (SIGINT), as a cleanup hook at the end of processing (SIGEXIT), or even as a custom messaging mechanism (SIGUSR1).
Trapping a signal is as easy as specifying a custom function name and the signal name as arguments.
# syntax: trap <custom_function> <SIGNAL> trap sigint_capture SIGINT trap sigusr1_capture USR1 trap sigexit_capture EXIT
The ‘sigusr1_capture’ function below displays a count of how many times the signal is called. The same goes for ‘sigint_capture’, and is called every time the user presses <Ctrl>-C. The ‘sigexit_capture’ is run at the end of the process, even if the script is ended abruptly.
sigusr1_count=0 function sigusr1_capture() { ((sigusr1_count+=1)) echo "SIGUSR1 called $sigusr1_count times" } ctrl_c_count=0 function sigint_capture() { ((ctrl_c_count+=1)) echo "SIGINT CTRL-C sensed for $ctrl_c_count time" } function sigexit_capture() { echo "== FINAL EXIT COUNTS ===" echo "SIGUSR1 called $sigusr1_count times" }
For a full example, see my test_trap.sh
REFERENCES
stackoverflow, sigstop and sigkill cannot be captured