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