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

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

首先介绍while语句。spa

[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结束循环语句。没有控制好循环条件容易造成死循环,程序无终止执行条件。code

再看一个例子。it

[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 不经常使用,简单了解便可。for循环

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

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

[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 ~]#
相关文章
相关标签/搜索