Skip to main content

Raymii.org 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 youhow to capture a Control C signal in a bash script, for example, to clean up anytemp or pid files when your script is killed or closed.

If you like this article, consider sponsoring me by trying out a Digital OceanVPS. 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 donot specify a number, a SIGTERM is sent. If you for example do a pkill -9firefox, it sents a SIGKILL. If you have a bash script which places a tempfile, 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 functionto 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 bindit to both SIGINT and SIGTERM:

trap control_c SIGINTtrap control_c SIGTERM

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

Read more about Signals here on The Linux Documentation Project

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