Bash to Basics: The For Loop
Previously I've shown how to use the bash while loop in a bash script. Today I'm going to show how to use another type of do loop in bash: the for loop.
The for loop is a little different from the other looping structures in bash. The other loop structures work by evaluating whether an expression is true or false. The for loop works on lists of values. As long as there are items left in the list, the for loop will execute.
Here's a basic example. Read more
Bash to Basics: The While Do Loop
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

