Breaking an infinite loop in a shell script

Friday, December 28, 2012 , , 0 Comments

How can I stop an infinite loop in a script?
Or in other words it can also be said like How to send a signal for an infinite loop in script and exit that loop gracefully?

It's quite simple. Below is a test script which will run into an infinite loop:
echo "My pid is: $$"
finish=0
trap 'finish=1' SIGUSR1
while (( finish != 1 ))
do
stuff
sleep 5
done
Execute this and if you want to test and while the script is executing in the background, do as below:
kill -SIGUSR1 pid
Where pid is the process id of the script.If the signal is raised during the
Sleep, it will wake up (sleep sleeps until any signal occurs) and exit the loop only gracefully.

0 comments: