Bash to Basics: The While Do Loop

September 13, 2009 by
Filed under: bash, linux 

The While Do Loop

One of the most common structures in programming is the Do Loop. The version that I'm going to show today is the While Do Loop. The basic structure of the While Do Loop is: while condition A exists, execute the loop. Here's an example program that counts to ten and then exits.

#!/bin/bash

x=0		# Initialize x as zero
while [ "$x" -lt "10" ]		# While x is less than ten, execute the do loop.
do sleep 0.1				# Sleep slows things down a bit.
	let "x += 1"			# Increment x.
	echo -en "$x "			# Print the value of x without the newline character.
done						# Complete the loop.
echo						# Move the prompt down to a new line.
exit 0

Copy the above program into a text editor and save it as a file called count. Then make sure to make it executable.

chmod +x count

You can now run the program with the command

./count

Notice that the control of the loop says to execute while x is less than ten, but the program counts all the way to ten before exiting. This is due to the increment x statement being before the echo statement. The loop gets entered while x equals nine, x gets incremented up to ten, and then printed to the standard output.

Affiliate Link

The Infinite Loop

You may have heard the terminology infinite loop. An infinite loop is usually caused by faulty programming logic that allows a loop to execute continuously. Here's an example of an infinite loop.

#!/bin/bash

###########################################
#                                         #
# This is an example of an infinite loop. #
#                                         #
###########################################

x=0			# Initialize x

while [ "$x" -eq "0" ]
do sleep 0.1				# Sleep slows things down a bit.
	echo "This is an infinite loop."
done
exit 0

Comments

4 Responses to “Bash to Basics: The While Do Loop”

  1. 007 says:

    Reminds of the good old BASIC command

    10 ? "WHAT THE!!!"
    20 GOTO 10
    RUN

    :)

  2. Story added...

    This story has been submitted to fsdaily.com! If you think this story should be read by the free software community, come vote it up and discuss it here:

    http://www.fsdaily.com/Beginner/Bash_to_Basics_The_While_Do_Loop...

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>