while & until cycle in bash

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 restart some program when it exits and get alerts if it stops. Its note quite the thing with nohup but still…

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

Add command line arguments to array and append to string

declare -A argumentarray
argumentstring="appending arguments to this string separated by comma: "

while [ $# -gt 0 ];do
  [ $# -ge 2 ] && argumentstring+=","

Loop trough each line of the file with while

# cycle trough each line in file
while read LINE; do 
echo "${LINE}"
done < inputfile

# OR pipe input to it
cat inputfile | while read LINE; do 
echo "${LINE}"

Until cycle runs until the condition is FALSE

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.