while 命令在某种程度上糅合了 if-then 语句和 for 循环。while 命令允许定义一个要测试的命令,只要该命令返回的退出状态码为 0,
就循环执行一组命令。它会在每次迭代开始时测试 test 命令,如果 test 命令返回非 0 退出状态码,while 命令就会停止执行循环。
(1)while 的基本格式
while 命令的格式如下:
while test command
do
other commands
done
(2)test command 最常见的用法是使用方括号来检查循环命令中用到的 shell 变量值:
$ cat test10
#!/bin/bash
# while command test
var1=10
while [ $var1 -gt 0 ]
do
echo $var1
var1=$[ $var1 - 1 ]
done
$ ./test10
(3)使用多个测试命令
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
$