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.
[term]
#!/bin/bash
for i in {one,two,three,four,five,six,seven,eight,nine,ten}
do
echo -en "$i " # Print each value without a newline character
sleep 0.5 # Slow things down with sleep
done # End the loop
echo # Move down to a new line
exit 0
[/term]
Like I said, the for loop will work on any list of values. Try replacing the above for statement with each of the following.
[term]
for i in {1,2,3,4,5,6,7,8,9,10}
for i in {1..10}
for i in `seq 10`
for (( i=1; i<=10; i++ ))
for (( i=1; i<0; i++ ))
[/term]
Do you know another way to control a for loop? Leave a comment.
Pingback: Links 20/2/2010: Ubuntu 10.04 Gets New Appearance, Jacobsen vs Katzer Victory | Boycott Novell
Pingback: fsdaily.com