本文是 Linux Shell 系列教程的第十二篇。前面我們已介紹過 for 迴圈與 while 迴圈,本篇要說明 Shell 中最後一種迴圈語句:until 迴圈。

until 迴圈與 while 迴圈很像,差別在於條件的判斷方向:while 測「真值」,until 則測「假值」。也就是說,當 until 的條件測試結果為假(傳回值不為 0)時才會持續迴圈,一旦為真(傳回值為 0)就跳出。
until command do Statement(s) to be executed until command is true done
command 為條件運算式,若傳回值為 false 則繼續執行迴圈體,否則跳出。
範例一:輸出 0 到 9。
#!/bin/bash a=0 until [ ! $a -lt 10 ] do echo $a a=`expr $a + 1` done
說明:當「a 不小於 10」這個條件為假時持續輸出,直到 a 大於等於 10 才跳出。
範例二:
#!/bin/bash declare -i i=10 declare -i sum=0 until ((i>10)) do let sum+=i let ++i done echo $sum
這個例子與上一篇的範例相似,但結果不同,不妨親手跑一跑,觀察其中的差異。
關於 until 迴圈的介紹就到這裡,更多內容請參閱 Linux Shell 系列教程。