
- Unix/Linux 初學者教程
- Unix/Linux - 首頁
- Unix/Linux - 什麼是 Linux?
- Unix/Linux - 快速入門
- Unix/Linux - 檔案管理
- Unix/Linux - 目錄
- Unix/Linux - 檔案許可權
- Unix/Linux - 環境變數
- Unix/Linux - 基本實用程式
- Unix/Linux - 管道 & 過濾器
- Unix/Linux - 程序
- Unix/Linux - 通訊
- Unix/Linux - vi 編輯器
- Unix/Linux Shell 程式設計
- Unix/Linux - Shell 指令碼
- Unix/Linux - 什麼是 Shell?
- Unix/Linux - 使用變數
- Unix/Linux - 特殊變數
- Unix/Linux - 使用陣列
- Unix/Linux - 基本運算子
- Unix/Linux - 決策語句
- Unix/Linux - Shell 迴圈
- Unix/Linux - 迴圈控制
- Unix/Linux - Shell 替換
- Unix/Linux - 引號機制
- Unix/Linux - I/O 重定向
- Unix/Linux - Shell 函式
- Unix/Linux - 手冊頁幫助
- 高階 Unix/Linux
- Unix/Linux - 標準 I/O 流
- Unix/Linux - 檔案連結
- Unix/Linux - 正則表示式
- Unix/Linux - 檔案系統基礎
- Unix/Linux - 使用者管理
- Unix/Linux - 系統性能
- Unix/Linux - 系統日誌
- Unix/Linux - 訊號和陷阱
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
廣告