一、while循環
while循環用于不斷執行一系列命令,也用于從輸入文件中讀取數據;命令通常為測試條件。其格式為:
代碼如下:
while 命令
do
command1
command2
...
commandN
done
命令執行完畢,控制返回循環頂部,從頭開始直至測試條件為假。
以下是一個基本的while循環,測試條件是:如果COUNTER小于5,那么條件返回真。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
二、until循環
until循環執行一系列命令直至條件為真時停止。until循環與while循環在處理方式上剛好相反。一般while循環優于until循環,但在某些時候—也只是極少數情況下,until循環更加有用。
until循環格式為:
代碼如下:until 條件
command1
command2
...
commandN
done
條件可為任意測試條件,測試發生在循環末尾,因此循環至少執行一次—請注意這一點。
新聞熱點
疑難解答