Linux shell - until
June 3, 2024Less than 1 minute
与 while 命令工作的方式完全相反,until 命令要求指定一个返回非 0 退出状态码的测试命令。只要测试命令的退出状态码不为 0,bash shell 就会执行循环中列出的命令。一旦测试命令返回了退出状态码 0,循环就结束了。
until 命令的格式如下:
until test commands
do
other commands
done
通过测试 var1 变量来决定 until 循环何时停止。只要该变量的值等于 0,until 命令就会停止循环。
var1=100
until [ $var1 -eq 0 ]
do
echo $var1
var1=$[ $var1 - 25 ]
done
# 100
# 75
# 50
# 25
与 while 命令类似,你可以在 until 命令语句中放入多个 test command。最后一个命令的退出状态码决定了 bash shell 是否执行已定义的 other commands。
var1=100
until echo $var1
[ $var1 -eq 0 ]
do
echo Inside the loop: $var1
var1=$[ $var1 - 25 ]
done
# 100
# Inside the loop: 100
# 75
# Inside the loop: 75
# 50
# Inside the loop: 50
# 25
# Inside the loop: 25
# 0