UNIX and Linux Shell Script While and Until Loops

While and Until loops check an exit status of a command. In both cases this check is made before deciding on wether or not to run an itteration of the code inside the loop. In the case of the Whille loop, the code inside the control flow is run while the check is true. In the case of the Until loop, the code is run until the check becomes true.

The While and Until Control Flow Basic Forms

The basic form of the While loop is:


while Check something
do
	# Runs code here while the check returns true
	Some Code 
done

The basic form of the Until loop is:


until Check something
do
	# Runs code here until the check returns true 
	Some Code
done

Example 1: A Sleepy Until Loop

Here’s an example of an until loop, used to wait until a file exists.

The script starts tomcat, then waits until a tomcat pid file has been created before it returns a success message.


bin/catalina.sh start # Command to start tomcat app server
until test -f tomcat.pid
do
	sleep 300
done	
echo "Tomcat has started"

Example 2: A While Loop

Shell scripters can be games writers too! Here’s an example of a script that makes use of a While loop:


echo "Are you bored? y/n"
read ANSWER
while test $ANSWER = "n"
do
	echo "How about now?"
	read ANSWER
done
echo "OK. Goodbye"

Adding the above code to a file called "dullgame" means that we can play the game like this:

bash$ sh dullgame
Are you bored? y/n
n
How about now?
n
How about now?
y
OK. Goodbye

Of course, there are many good uses for While and Until loops too. Have fun looking out for them!