您的位置:首页 > 运维架构 > Shell

Linux Shell系列教程(十三)之Shell while和until循环

2017-12-01 11:32 671 查看
Linux下一条命令或一个进程执行完成会返回一个一个状态码。

0 === 成功执行

非0 === 执行过程中出现异常或非正常退出

while循环

while循环用于不断执行一系列命令,也用于从输入文件中读取数据;命令通常为测试条件。其格式为:

while command

do

Statement(s) to be executed if command is true

done

命令执行完毕,控制返回循环顶部,从头开始直至测试指令返回非零退出状态码时,while命令会停止循环。

即:条件成立则循环

不成立则停止循环

(1)计数器控制的while循环

#!/bin/bash
sum=0
i=0
while(( i <= 100 ))
do
let "sum+=i"
let "i += 2"
done
echo "sum=$sum"


指定了循环的次数50,初始化计数器值为0,不断测试循环条件i是否小于等于100。在循环条件中设置了计数器加2来计算1~100内所有的偶数之和。

(2)结束标记控制的while循环

设置一个特殊的数据值(结束标记)来结束while循环。

#!/bin/bash
echo "Please input the num(1-10) "
read num

while [[ "$num" != 5 ]]
do
if [ "$num" -lt 5 ]
then
echo "Too small. Try again!"
read num
elif [ "$num" -gt 5 ]
then
echo "To high. Try again"
read num
else
exit 0
fi
done

echo "Congratulation, you are right! "


执行结果:

Please input the num(1-10)
7
To high. Try again
4
Too small. Try again!
5
Congratulation, you are right!


(3)命令行控制的while循环

#!/bin/bash
a=1
read -p "Please enter a number:"  sam
#小于等于
while [ $a -le $sam ]
do
echo $a
let a++
done
echo "after while ,a= $a"


Please enter a number:4
1
2
3
4
after while ,a= 5


(4)使用多个测试命令

只有最后一个测试命令的退出状态码会被用来决定什么时候结束循环;

#!/bin/bash
a=5
b=2
while echo $a;[ $b -ge 0 ]; [ $a -ge 0 ]
do
echo "this is inside the loop a=$a;  b=$b"
let a--
let b--
done
echo "after while ,a= $a";b=$b


执行结果:

5
this is inside the loop a=5;  b=2
4
this is inside the loop a=4;  b=1
3
this is inside the loop a=3;  b=0
2
this is inside the loop a=2;  b=-1
1
this is inside the loop a=1;  b=-2
0
this is inside the loop a=0;  b=-3
-1
after while ,a= -1;b=-4


含多个命令的while语句中,在每次迭代中所有的测试命令都会被执行,包括测试命令失败的最后一次迭代。

2.until循环

until命令和while命令的工作方式完全相反

即:条件成立则停止循环

不成立则循环

#!/bin/bash
sum=0
i=0
until (( i >= 10 ))
do
let "sum+=i"
let "i += 2"
echo "i=$i"
done
echo "sum=$sum"


执行结果:

i=2
i=4
i=6
i=8
i=10
sum=20


当i大于等于10时成立,则停止循环

多条件同while指令一样!

只有最后一个命令成立时停止
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: