shell_30.Linux使用while命令

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 
$

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

微辣已是极限

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值