Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop infinite loop in bash script gracefully?

I need to run application in every X seconds, so, as far as cron does not work with seconds this way, I wrote a bash script with infinite loop having X seconds sleep in it.

When I have to stop the running script manually, I would like to do it in a correct way - let the application complete functioning and just do not enter the loop for the next time.

Do you have any idea, how this can be achieved? I thought about passing arguments, but I could not find how to pass argument to running script.

like image 918
Samurai Girl Avatar asked Jun 26 '12 08:06

Samurai Girl


1 Answers

You could trap a signal, say SIGUSR1:

echo "My pid is: $$"
finish=0
trap 'finish=1' SIGUSR1

while (( finish != 1 ))
do
    stuff
    sleep 42
done

Then, when you want to exit the loop at the next iteration:

kill -SIGUSR1 pid

Where pid is the process-id of the script. If the signal is raised during the sleep, it will wake (sleep sleeps until any signal occurs).

like image 174
cdarke Avatar answered Sep 17 '22 13:09

cdarke