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.
You can now run the program with the command
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.
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
#
#
Reminds of the good old BASIC command
10 ? "WHAT THE!!!"
20 GOTO 10
RUN
🙂
#
Yeah, this is basically a re-creation of one of my first BASIC programs.
#