Linux shell - while
while 命令在某种程度上糅合了 if-then 语句和 for 循环。while 命令允许定义一个要测试的命令,只要该命令返回的退出状态码为 0,就循环执行一组命令。它会在每次迭代开始时测试 test 命令,如果 test 命令返回非 0 退出状态码,while 命令就会停止执行循环。
while 命令的格式如下:
while test command
do
other commands
done
while 命令中定义的 test command 与 if-then 语句中的格式一模一样。可以使用任何 bash shell 命令,或者用 test command 进行条件测试,比如测试变量值。
while 命令的关键在于所指定的 test command 的退出状态码必须随着循环中执行的命令而改变。如果退出状态码不发生变化,那 while 循环就成了死循环。
test command 最常见的用法是使用方括号来检查循环命令中用到的 shell 变量值:
var1=10
while [ $var1 -gt 0 ]
do
echo $var1
var1=$[ $var1 - 1 ]
done
# 10
# 9
# 8
# 7
# 6
# 5
# 4
# 3
# 2
# 1
while 命令定义了每次迭代时检查的测试条件:
while [ $var1 -gt 0 ]
只要测试条件成立,while 命令就会不停地循环执行定义好的命令。必须在这些命令中修改测试条件中用到的变量,否则就会陷入死循环。这里使用 shell 算术将变量值减 1:
var1=$[ $var1 - 1 ]
while 循环会在测试条件不再成立时停止。
while 命令允许在 while 语句行定义多个测试命令。只有最后一个测试命令的退出状态码会被用于决定是否结束循环。如果你不小心,这可能会导致一些有意思的结果。下面的例子会说明这一点:
var1=10
while echo $var1
[ $var1 -ge 0 ]
do
echo "This is inside the loop"
var1=$[ $var1 - 1 ]
done
# 10
# This is inside the loop
# 9
# This is inside the loop
# 8
# This is inside the loop
# 7
# This is inside the loop
# 6
# This is inside the loop
# 5
# This is inside the loop
# 4
# This is inside the loop
# 3
# This is inside the loop
# 2
# This is inside the loop
# 1
# This is inside the loop
# 0
# This is inside the loop
# -1
第一个测试简单地显示了 var1 变量的当前值。第二个测试用方括号来判断 var1 变量的值。在循环内部,echo 语句会显示一条简单的消息,说明循环被执行了。
在含有多个命令的 while 语句中,在每次迭代时所有的测试命令都会被执行,包括最后一个测试命令失败的末次迭代。要小心这一点。另一处要留意的是该如何指定多个测试命令。注意要把每个测试命令都单独放在一行中。