Linux Shell 之 while 循环语句
while命令某种意义上是if-then语句和for循环的混杂体。while命令允许定义一个要测试的命令,然后循环执行一组命令,只要定义的测试命令返回的是退出状态码0。它会在每次迭代的一开始测试test命令。在test命令返回非零退出状态码时,while命令会停止执行那组命令。
1.1、while 的基本格式
while命令的格式是:
1 while test command 2 do 3 other commands 4 done
while命令中定义的test command和if-then语句(参见第12章)中的格式一模一样。可以使用任何普通的bash shell命令,或者用test命令进行条件测试,比如测试变量值。
while命令的关键在于所指定的test command的退出状态码必须随着循环中运行的命令而改变。如果退出状态码不发生变化, while循环就将一直不停地进行下去。
最常见的test command的用法是用方括号来检查循环命令中用到的shell变量的值。
1 $ cat test10 2 #!/bin/bash 3 # while command test 4 var1=10 5 while [ $var1 -gt 0 ] 6 do 7 echo $var1 8 var1=$[ $var1 - 1 ] 9 done 10 $ ./test10 11 10 12 9 13 8 14 7 15 6 16 5 17 4 18 3 19 2 20 1 21 $
while命令定义了每次迭代时检查的测试条件:
1 while [ $var1 -gt 0 ]
只要测试条件成立,while命令就会不停地循环执行定义好的命令。在这些命令中,测试条件中用到的变量必须修改,否则就会陷入无限循环。在本例中,我们用shell算术来将变量值减一:
1 var1=$[ $var1 - 1 ]
while循环会在测试条件不再成立时停止。
1.2、使用多个测试命令
while命令允许你在while语句行定义多个测试命令。只有最后一个测试命令的退出状态码会被用来决定什么时候结束循环。如果你不够小心,可能会导致一些有意思的结果。下面的例子将说明这一点。
1 $ cat test11 2 #!/bin/bash 3 # testing a multicommand while loop 4 var1=10 5 while echo $var1 6 [ $var1 -ge 0 ] 7 do 8 echo "This is inside the loop" 9 var1=$[ $var1 - 1 ] 10 done 11 $ ./test11 12 10 13 This is inside the loop 14 9 15 This is inside the loop 16 8 17 This is inside the loop 18 7 19 This is inside the loop 20 6 21 This is inside the loop 22 5 23 This is inside the loop 24 4 25 This is inside the loop 26 3 27 This is inside the loop 28 2 29 This is inside the loop 30 1 31 This is inside the loop 32 0 33 This is inside the loop 34 -1 35 $
请仔细观察本例中做了什么。while语句中定义了两个测试命令。
1 while echo $var1 2 [ $var1 -ge 0 ]
第一个测试简单地显示了var1变量的当前值。第二个测试用方括号来判断var1变量的值。在循环内部,echo语句会显示一条简单的消息,说明循环被执行了。注意当你运行本例时输出是如何结束的。
1 This is inside the loop 2 -1 3 $
while循环会在var1变量等于0时执行echo语句,然后将var1变量的值减一。接下来再次执行测试命令,用于下一次迭代。echo测试命令被执行并显示了var变量的值(现在小于0了)。直到shell执行test测试命令,whle循环才会停止。
这说明在含有多个命令的while语句中,在每次迭代中所有的测试命令都会被执行,包括测试命令失败的最后一次迭代。要留心这种用法。另一处要留意的是该如何指定多个测试命令。注意,每个测试命令都出现在单独的一行上。