Skip to main content

Raymii.org Raymii.org Logo

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

Bash Bits: Trap Control C (SIGTERM)

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


❗ This post is over eleven years old. It may no longer be up to date. Opinions may have changed.

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.

Recently I removed all Google Ads from this site due to their invasive tracking, as well as Google Analytics. Please, if you found this content useful, consider a small donation using any of the options below:

I'm developing an open source monitoring app called Leaf Node Monitoring, for windows, linux & android. Go check it out!

Consider sponsoring me on Github. It means the world to me if you show your appreciation and you'll help pay the server costs.

You can also sponsor me by getting a Digital Ocean VPS. With this referral link you'll get $200 credit for 60 days. Spend $25 after your credit expires and I'll get $25!

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