Syntax:
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
The for loop first creates i variable and assigned a number to i from the list of number from 1 to 5, The shell execute echo statement for each assignment of i. (This is usually know as iteration) This process will continue until all the items in the list were not finished, because of this it will repeat 5 echo statements
#Script to test for loop
#
#
if [ $# -eq 0 ]
then
echo "Error - Number missing form command line argument"
echo "Syntax : $0 number"
echo "Use to print multiplication table for given number"
exit 1
fi
n=$1
for i in 1 2 3 4 5 6 7 8 9 10
do
echo "$n * $i = `expr $i \* $n`"
done
Even you can use following syntax:
Syntax:
for (( expr1; expr2; expr3 )) do ..... ... repeat all statements between do and done until expr2 is TRUE Done
注意:这种格式的for Loop仅仅支持bin/bash,不支持bin/sh。
In above syntax BEFORE the first iteration, expr1 is evaluated. This is usually used to initialize variables for the loop.
All the statements between do and done is executed repeatedly UNTIL the value of expr2 is TRUE.
AFTER each iteration of the loop, expr3 is evaluated. This is usually use to increment a loop counter.
eg.
for (( i = 0 ; i <= 5; i++ ))
do
echo "Welcome $i times"
done
$ vim chessboard
for (( i = 1; i <= 9; i++ )) ### Outer for loop ###
do
for (( j = 1 ; j <= 9; j++ )) ### Inner for loop ###
do
tot=`expr $i + $j`
tmp=`expr $tot % 2`
if [ $tmp -eq 0 ]; then
echo -e -n "\033[47m "
else
echo -e -n "\033[40m "
fi
done
echo -e -n "\033[40m" #### set back background colour to black
echo "" #### print the new line ###
done