Shell while循環


while循環用於不斷執行一系列命令,也用於從輸入文件中讀取數據;命令通常為測試條件。其格式為:

while command
do
   Statement(s) to be executed if command is true
done

命令執行完畢,控制返回循環頂部,從頭開始直至測試條件為假。

以下是一個基本的while循環,測試條件是:如果COUNTER小於5,那么返回 true。COUNTER從0開始,每次循環處理時,COUNTER加1。運行上述腳本,返回數字1到5,然后終止。

  1. COUNTER=0
  2. while [ $COUNTER -lt 5 ]
  3. do
  4. COUNTER='expr $COUNTER+1'
  5. echo $COUNTER
  6. done

運行腳本,輸出:

1
2
3
4
5


while循環可用於讀取鍵盤信息。下面的例子中,輸入信息被設置為變量FILM,按<Ctrl-D>結束循環。

  1. echo 'type <CTRL-D> to terminate'
  2. echo -n 'enter your most liked film: '
  3. while read FILM
  4. do
  5. echo "Yeah! great film the $FILM"
  6. done

運行腳本,輸出類似下面:

type <CTRL-D> to terminate
enter your most liked film: Sound of Music
Yeah! great film the Sound of Music


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM