for Loop
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
do
echo "Welcome $i times"
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
Nesting of for Loop
Following script is quite intresting, it prints the chess board on screen.$ 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

本文详细介绍了Shell脚本中for循环的两种语法形式:基于列表的for循环和基于表达式的for循环,并通过实例展示了如何使用这些循环进行迭代操作及嵌套循环的应用。

被折叠的 条评论
为什么被折叠?



