Searching...
June 3, 2013

Trapping CTRL C in Bash Scripting

Hey guys... I wanna share something with shell scripting. In this case, my shell is bash which you can find on any Linux platform.

So, let's talk about bash scripting. You may wonder, how to prevent CTRL+C to interrupt your shell script? But it depend on something actually. How long your bash script? If it just took 1-3 seconds, you may don't need this function actually. But, how about if it took 10 - 60 seconds to finish? It will be "fatal" it's interrupted by CTRL+C, especially in critical function.

I got the script like this

#!/bin/bash

while sleep 1; do
echo "I'm still alive"

done

This script will spawn output "I'm still alive" EVERY second. And exit 0 will never be reach, which means this script will never been finish FOREVER, EXCEPT you interrupt it by pressing CTRL+C or CTRL+Z.

How to tell if CTRL+C is pressed?

Well let's start from trap function. Let's add trap function in this script.

#!/bin/bash

interrupt()
{
echo "CTRL C is being pressed"
}

trap 'interrupt' INT

while true; do
echo "I'm still alive"
done

When we press CTRL C
CTRL C is being pressed, however the script still running. You can stop this by pressing CTRL + Z, then CTRL + D.

Let's make this being more friendly, by asking users whether they want to exit or not.

#!/bin/bash

interrupt()
{
echo "CTRL C is being pressed"
 ask=true
 while [ $ask == "true" ]
 do
 echo -ne "Do you really want to exit (y/n): "
 read answer
 if [ $answer == "y" ]; then
 echo "Exiting..."
 exit 0
 ask=false
 elif [ $answer == "n" ]; then
 echo "Rock on"
 ask=false
 else
 echo "Wrong input pals..."
 ask=true
 fi
 done

}

trap 'interrupt' INT

while true; do
sleep 1
echo "I'm still alive"
done

The script will ask users, whether they want to exit or not. If they type y (which mean yes), the script will exit with 0 code (which mean has finished). If they type n (which mean no), the script will go on. Let's try this again.

Pressing y
Pressing n

 
Back to top!