| < Day Day Up > |
|
From time to time anyone who writes scripts will find an occasion to repeat a set of commands for a certain number of times. This is referred to as a loop. The type of loop used most often in Linux shell scripts is the for loop. The general concept of a for loop is for as long as some condition is true, keep looping. The general concept of a while loop is similar. It is while some condition is true, keep looping.
There are a few rules that apply to all loops in shell scripts.
The variable used in the loop condition must be initialized before execution of the loop begins.
A test to see if the loop’s conditions are met is made at the beginning of each iteration.
The body of a loop ends with a statement that modifies the value of the test variable.
The basic syntax of a for loop is this:
for { variable name } in { list } do execute one for each item in the list until the list is not finished (and repeat all statement between do and done) done
Let’s take a look at a script that illustrates the for loop. Type the following lines into the text editor of your choice and save it as scriptten.sh:
#!/bin/bash echo Count down for i in 1 2 3 4 5 do echo $i done echo blast off! exit 0
If you run this from the shell, you should see something like what is displayed in Figure 20.15.
Figure 20.15: The for loop.
You can see that a for loop is simple. Take a variable named i and count through the numbers 1 through 5, assigning that variable to i in each loop. Each time, echo that value to the screen. In other words, take the variable i, start it off with a value of 1, and keep incrementing through a value of 5.
| < Day Day Up > |
|