Content #
while命令允许在while语句行定义多个测试命令。只有最后一个测试命令的退出状态码会被用于决定是否结束循环。
$ cat test11
#!/bin/bash
# testing a multicommand while loop
var1=10
while echo $var1
[ $var1 -ge 0 ]
do
echo "This is inside the loop"
var1=$[ $var1 - 1 ]
done
$ ./test11
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
$
在while语句中定义了两个测试命令:
while echo $var1
[ $var1 -ge 0 ]
第一个测试简单地显示了var1变量的当前值。第二个测试用方括号来判断var1变量的值。在循环内部,echo语句会显示一条简单的消息,说明循环被执行了。注意在运行本例时,输出是如何结束的。 This is inside the loop -1 $ while循环会在var1变量等于0时执行echo语句,然后将var1变量的值减1。接下来再次执行测试命令,判断是否进行下一次迭代。首先执行echo测试命令,显示 var变量的值(小于0)。接着执行test命令,因为条件不成立,所以while循环停止。
这说明在含有多个命令的while语句中,在每次迭代时所有的测试命令都会被执行,包括最后一个测试命令失败的末次迭代。要小心这一点。另一处要留意的是该如何指定多个测试命令。注意要把每个测试命令都单独放在一行中。
From #
Linux命令行与shell脚本编程大全