Linux shell script: while loop and sleep example

Linux shell script FAQ: Can you share a Linux shell script while loop example? While you’re at it, can you show how to use the sleep command in the shell script while loop?

Sure. As a little background, I’ve written a program I call an Email Agent that periodically scans my email inbox, and does a lot of things to the inbox, including deleting the over 6,000 spams that I receive in a typical day. A recent problem with the Agent is that it runs too fast, apparently overwhelming the sendmail process on the machine that it runs on.

To help keep sendmail alive, I slow my program down in two ways. First, I try to get it to go through messages more slowly. Because the program is written in Java, I accomplish that with the Thread.sleep call in my Java code. Second, I pause the program by calling the Unix/Linux sleep command from my Bourne shell script.

Sleeping in a shell script while loop

As an example of both a while loop and sleep command, here is how my Email Agent program is now run from inside a Bourne shell script:

i=1
while [ "$i" -ne 0 ]
do
  i=./runEmailAgent
  sleep 10
done

Basically what happens is that my Email Agent program is called by my shell script, and then the Email Agent program returns a numeric value when it is finished running. A value of zero means it is finished doing all it can do, while any other number means it still has work to do, but stopped itself to give sendmail a break. After that, I give sendmail a second break by calling the Linux sleep command. I tell the sleep command to take a break for 10 seconds. When ten seconds has come and gone, the test in the while block is run again.

Linux shell script while loop and sleep example

If you ever wanted to write a while loop in the Bourne shell, I hope this serves as a simple example. Please note that it is very easy to create an infinite loop here, so be careful that the program you call will actually return a zero value at some time (assuming you decide to implement the loop exactly as shown above).

I’ve also written many other Linux shell script while loop examples. For more information, just search this site, or see the “Related” section for other while loop and shell script tips.