while命令2--shell脚本

while命令允许你在while语句定义多个测试命令。只有在最后一个测试命令的退出状态码会被用来决定什么时候结束循环。如果你不够小心,可能会导致一些有意思的结果。下面的例子将会说明这一点。

[root@ecs robin]# cat while2.sh
#! /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

执行结果:

[root@ecs robin]# ./while2.sh
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的变量的值减一。接下来再次执行测试命令,用于下一次迭代。echo测试命令被执行并显示var变量的值(现在小于0了)。知道shell执行test测试命令,while循环才会停止。

  这说明在含有多个命令的while语句中,在每次迭代中所有的测试命令都会被执行,包括测试命令失败的最后一次迭代。要留心这种用法。另一处要刘毅的是该如何执行多个测试命令。注意,每个测试命令都出现在单独的一行上。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值