歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> Shell while循環

Shell while循環

日期:2017/3/3 17:16:49   编辑:SHELL編程
while循環用於不斷執行一系列命令,也用於從輸入文件中讀取數據;命令通常為測試條件。其格式為:
while command
do
   Statement(s) to be executed if command is true
done
命令執行完畢,控制返回循環頂部,從頭開始直至測試條件為假。

以下是一個基本的while循環,測試條件是:如果COUNTER小於5,那麼返回 true。COUNTER從0開始,每次循環處理時,COUNTER加1。運行上述腳本,返回數字1到5,然後終止。
COUNTER=0
while [ $COUNTER -lt 5 ]
do
    COUNTER='expr $COUNTER+1'
    echo $COUNTER
done
運行腳本,輸出:
1
2
3
4
5

while循環可用於讀取鍵盤信息。下面的例子中,輸入信息被設置為變量FILM,按<Ctrl-D>結束循環。
echo 'type <CTRL-D> to terminate'
echo -n 'enter your most liked film: '
while read FILM
do
    echo "Yeah! great film the $FILM"
done
運行腳本,輸出類似下面:
type <CTRL-D> to terminate
enter your most liked film: Sound of Music
Yeah! great film the Sound of Music
Copyright © Linux教程網 All Rights Reserved