CentOS 7 Shell脚本编程第十三讲 循环语句

循环语句主要有while do while for select等,循环语句主要用于重复执行命令,直到达到终止循环条件。

首先介绍while语句。


[root@promote ~]# cat testwhilev1.0.sh 
#!/bin/bash
num=0
while (( num <2 ))
do
((num++))
echo $num
done 
[root@promote ~]# bash testwhilev1.0.sh 
1
2

while 语句表达式成立时,执行语句。条件不成立执行done结束循环语句。没有控制好循环条件容易形成死循环,程序无终止执行条件。

再看一个例子。

[root@promote ~]# cat testwhilev1.1.sh
#!/bin/bash
count=0
while [[ $count < 5 ]] 
do
    ((count ++ ))
    echo $count
done
[root@promote ~]# bash testwhilev1.1.sh
1
2
3
4
5
[root@promote ~]# 
#思考问题,代码执行完毕$count等于几?

until 作用和 while 相反,循环条件不成立执行语句,直到条件成立为止。until 不常用,简单了解即可。

while 和 until 语句都含有 do done 结构。

for循环类似while循环。先看示例代码。本段代码执行结果为打印1到3。

[root@promote ~]# cat testif.sh
#!/bin/bash
for (( i=1; i<=3; i++ ))
do
	echo $i
done
[root@promote ~]# bash testif.sh
1
2
3
[root@promote ~]# 

for循环也可以制造死循环。

#死循环,需要强制退出
[root@promote ~]# cat testifv1.1.sh
#!/bin/bash
for (( i=1;; i++))
do
echo $i
done
[root@promote ~]# 

#倒序打印
[root@promote ~]# cat testforv1.2.sh
#!/bin/bash
for (( i=5;i>0;i-- ))
do
echo $i
done
[root@promote ~]# bash testforv1.2.sh
5
4
3
2
1
[root@promote ~]

根据代码可知for ( ) 内语句块分别为初始条件,判断条件,为true退出,可选,循环语句,可选。需要注意括号内两个分号不要遗漏

select循环和其他循环不同。

[root@promote ~]# cat testselectv1.0.sh
#!/bin/bash
select name in bill tom john carry linda 
do
    echo $name
    exit
done
#操作中输入2,输入完成退出
[root@promote ~]# bash testselectv1.0.sh
1) bill
2) tom
3) john
4) carry
5) linda
#? 2
tom
#错误输入无输出
[root@promote ~]# bash testselectv1.0.sh
1) bill
2) tom
3) john
4) carry
5) linda
#? 7

[root@promote ~]# 

 

转载于:https://my.oschina.net/u/1011130/blog/3031567

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值