Linux Shell 之 until循環語句


一、until 命令

  until命令和while命令工作的方式完全相反。until命令要求你指定一個通常返回非零退出狀態碼的測試命令。只有測試命令的退出狀態碼不為0,bash shell才會執行循環中列出的命令。一旦測試命令返回了退出狀態碼0,循環就結束了。
  和你想的一樣,until命令的格式如下。

1 until test commands 2 do
3  other commands 4 done

 

  和while命令類似,你可以在until命令語句中放入多個測試命令。只有最后一個命令的退出狀態碼決定了bash shell是否執行已定義的other commands。
  下面是使用until命令的一個例子。

 1 $ cat test12  2 #!/bin/bash  3 # using the until command  4 var1=100
 5 until [ $var1 -eq 0 ]  6 do
 7 echo $var1  8 var1=$[ $var1 - 25 ]  9 done
10 $ ./test12 11 100
12 75
13 50
14 25
15 $

 

  本例中會測試var1變量來決定until循環何時停止。只要該變量的值等於0,until命令就會停止循環。同while命令一樣,在until命令中使用多個測試命令時要注意。

 1 $ cat test13  2 #!/bin/bash  3 # using the until command  4 var1=100
 5 until echo $var1  6 [ $var1 -eq 0 ]  7 do
 8 echo Inside the loop: $var1  9 var1=$[ $var1 - 25 ] 10 done
11 $ ./test13 12 100
13 Inside the loop: 100
14 75
15 Inside the loop: 75
16 50
17 Inside the loop: 50
18 25
19 Inside the loop: 25
20 0
21 $

 

  shell會執行指定的多個測試命令,只有在最后一個命令成立時停止。


免責聲明!

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



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