Skip to main content Logo (IEC resistor symbol) logo

Quis custodiet ipsos custodes?
Home | About | All pages | RSS Feed | Gopher

Bash Bits: Trap Control C (SIGTERM)

Published: 14-09-2013 | Author: Remy van Elst | Text only version of this article

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.

If you like this article, consider sponsoring me by trying out a Digital Ocean VPS. With this link you'll get $100 credit for 60 days). (referral link)

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/
    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 , snippets