linux shell----for Loop

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

for i in 1 2 3 4 5
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

chessboard shell script output i.e. chess board














































發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章