while循環用於不斷執行一系列命令,也用於從輸入文件中讀取數據;命令通常為測試條件。其格式為:
while command do Statement(s) to be executed if command is true done
命令執行完畢,控制返回循環頂部,從頭開始直至測試條件為假。
以下是一個基本的while循環,測試條件是:如果COUNTER小於5,那么返回 true。COUNTER從0開始,每次循環處理時,COUNTER加1。運行上述腳本,返回數字1到5,然后終止。
#!/bin/bash COUNTER=0 while [ $COUNTER -lt 5 ] do COUNTER=$(expr $COUNTER + 1) echo $COUNTER done
運行腳本,輸出:
2 3 4 5
while循環可用於讀取鍵盤信息。下面的例子中,輸入信息被設置為變量FILM,按<Ctrl-D>結束循環
#!/bin/bash echo 'type <CTRL-D> to terminate' echo -n 'enter your most liked file: ' while read FILM do echo "Yeah! great file the $FILE" done
運行結果:
type <CTRL-D> to terminate
enter your most liked film: Sound of Music
Yeah! great film the Sound of Music