While cycle runs until the condition is true

This while cycle generates random numbers in range from 0 to 1000 and exits if number is greater than 900.

while true ; do x=$[ ( $RANDOM % 1000 ) ]; echo $x; if [ $x -gt 900 ]; then break; fi;done


Runs in background and runs something.sh as soon as there is no more .lock files in the current directory. 1 second sleep between checks.

while ls *.lock &> /dev/null ; do sleep 1;done && something.sh &


Keeps something.sh running. As soon as something.sh exits because of some reason, it runs alert.sh and starts something.sh again. Quite easy way to keep some program running no matter what and get alerts if it stops.

while true; do something.sh; alert.sh;done


Random service interrupts – run service with downtimes up to 1800sec and uptimes up to 3600sec

while true ; do X=$[ ( $RANDOM % 1800 ) ]; echo "Down for ${X} seconds"; service httpd stop; sleep ${X}; Y=$[ ( $RANDOM % 3600 ) ]; echo "Up for ${Y} seconds"; service httpd start; sleep ${Y}; done

If you want to run cycle until condition is false, replace while with until, it’s identical to while but with negated condition.  As an example, following would be infinite loop with until:

until false ; do echo "Echoing to infinity"; done

Check out also for cycle

If you found this useful, say thanks, click on some banners or donate, I can always use some beer money.

Leave a Reply

Your email address will not be published. Required fields are marked *