Bash Scripting – TRAP

Many of us might have faced a stiuation where we have started a script, waiting for its outcome and suddenly someone/ourself do a CTRL+C by mistake to terminate the script. Wouldn’t it be nice if our script becomes ‘immune’ to CTRL+C signal. Here comes ‘trap’ command for help.

‘trap’ command basically traps the signal which we have listed and performs the actions we have specified.

Below is a script you can try to make the script immune to CTRL+C signal.

#!/bin/bash
trap 'echo "This is not allowed"' SIGINT
CNT=1
while true; do
echo "This is iteration ${CNT}."
CNT=$((CNT + 1))
sleep 1
done

Output of the script


$ ./trial.sh
This is iteration 1.
This is iteration 2.
This is iteration 3.
This is iteration 4.
This is iteration 5.
This is iteration 6.
^CThis is not allowed
This is iteration 7.
This is iteration 8.
This is iteration 9.
This is iteration 10.
This is iteration 11.
^CThis is not allowed
This is iteration 12.
This is iteration 13.
This is iteration 14.
This is iteration 15.
^CThis is not allowed
This is iteration 16.

In general, with ‘trap’ you can trap signals and specify what actions are to be performed by the process.

 

Neelesh Gurjar has written 122 articles

Leave a Reply