Unix/Linux - Shell 迴圈型別



本章將討論 Unix 中的 Shell 迴圈。迴圈是一種強大的程式設計工具,使您可以重複執行一組命令。本章將介紹 Shell 程式設計師可用的以下幾種迴圈型別:

根據實際情況選擇不同的迴圈。例如,**while** 迴圈在給定條件為真時重複執行給定的命令;**until** 迴圈在給定條件變為真時才停止執行。

一旦您具備良好的程式設計實踐,您將獲得專業知識,從而開始根據情況使用合適的迴圈。這裡,**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
廣告