Handling terminal signals in bash scripts

Posted on March 30, 2019 in Linux

trap is the command that we are interested in. It listens for a interrupt signal and runs the command/function that has been specified.

Let's first define a function that we want to run before exiting:

user_interrupt(){
    echo "Received Keyboard Interrupt from User"
    echo "Exiting..."
}

Now you tell trap to listen for interrupts and run this function in case of such events:

trap user_interrupt SIGINT
trap user_interrupt SIGSTOP

With something like this at the beginning of your script, user_interrupt function is run if SIGINT or SIGSTOP signal is received.

The End.