Bash Bits: Trap Control C (SIGTERM)

14-09-2013 | Remy van Elst


Table of Contents


Bash Bits are small examples and tips for Bash Scripts. This bash bit shows you how to capture a Control C signal in a bash script, for example, to clean up any temp or pid files when your script is killed or closed.

All Bash Bits can be found using this link

Exit signals are sent when for example you use pkill or killall. If you do not specify a number, a SIGTERM is sent. If you for example do a pkill -9 firefox, it sents a SIGKILL. If you have a bash script which places a temp file, or a pid file, you might want to clean that up before you exit.

We create a function to catch the exit signals first, then we bind this function to the exit signals.

This is the control_c function:

function control_c {
    echo -en "\n## Caught SIGINT; Clean up and Exit \n"
    rm /var/run/myscript.pid
    exit $?
}

Then we use the trap command to bind the function to an exit signal. Here I bind it to both SIGINT and SIGTERM:

trap control_c SIGINT
trap control_c SIGTERM

Now when the script gets killed or you do a control c, the script will remove it's pid file. You can put anything in the control_c function, I mostly use it for cleanup.

Read more about Signals here on The Linux Documentation Project


Tags: bash, bash-bits, control-c, exit-signals, shell, sigterm,