迴圈是一個強大的編程工具,使您能夠重複執行一組命令。在本教程中,您將學習以下類型的迴圈Shell程式:
你會根據不同情況使用不同的迴圈。例如用 while 迴圈執行命令,直到給定的條件下是 ture ,迴圈直到執行到一個給定的條件為 false。
有良好的編程習慣,將開始使用情況的基礎上適當的迴圈。這裏while和for迴圈類似在大多數其他的編程語言,如C,C++ 和 Perl 等。
嵌套迴圈:
所有支持嵌套迴圈的概念,這意味著可以把一個迴圈內其他類似或不同的迴圈。這種嵌套可以去高達無限數量的時間根據需要。
嵌套的while迴圈和類似的方式,可以嵌套其他迴圈的基礎上的編程要求下麵是一個例子:
嵌套while迴圈:
作為另一個while迴圈的身體的一部分,這是可以使用一個while迴圈。
語法:
while command1 ; # this is loop1, the outer loop do Statement(s) to be executed if command1 is true while command2 ; # this is loop2, the inner loop do Statement(s) to be executed if command2 is true done Statement(s) to be executed if command1 is true done
例如:
這裏是迴圈嵌套一個簡單的例子,讓我們添加另一個倒計時迴圈內的迴圈,數到九:
#!/bin/sh a=0 while [ "$a" -lt 10 ] # this is loop1 do b="$a" while [ "$b" -ge 0 ] # this is loop2 do echo -n "$b " b=`expr $b - 1` done echo a=`expr $a + 1` done
這將產生以下結果。重要的是要注意 echo -n 是如何工作。在這裏,-n選項echo ,以避免列印一個新行字元。
0 1 0 2 1 0 3 2 1 0 4 3 2 1 0 5 4 3 2 1 0 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
上一篇:
Shell case...esac 語句
下一篇:
Shell while 迴圈