除了 if...then...fi 这种条件判断式之外,回圈可能是程序当中最重要的一环了~回圈可以不断的运行某个程序段落,直到使用者配置的条件达成为止。 所以,重点是那个『条件的达成』是什么。除了这种依据判断式达成与否的不定回圈之外, 还有另外一种已经固定要跑多少次的回圈形态,可称为固定回圈的形态呢!底下我们就来谈一谈:
while do done, until do done (不定回圈)
一般来说,不定回圈最常见的就是底下这两种状态了:
1.当 condition 条件成立时,就进行回圈,直到 condition 的条件不成立才停止:
while [condition] -->中括号内的状态就是判断式
do -->回圈的开始
程序段落
done -->回圈的结束
2.当 condition 条件成立时,就终止回圈,否则就持续进行回圈的程序段:
until [condition]
do
程序段
done
实例一:
#!/bin/bash
#Repeat question until input correct answer.
while [ "$yn" != "yes" -a "$yn" != "YES" ]
do
read -p "Please input yes/YES to stop this program:" yn
done
echo "Oh,you input the correct answer!"
实例二:
#!/bin/bash
#Repeat question until user input the correct answer!
until [ "$yn" == "yes" -o "$yn" == "YES" ]
do
read -p "Please input yes/YES to stop this program:" yn
done
echo "oh,you input the correct answer!"
比较一下有什么不同\(^o^)/~
如果我想要计算 1+2+3+....+100 这个数据呢? 利用回圈啊
#!/bin/bash
#The program will use loop to calculate "1+2+3..+100"
i=0
sum=0
while [ "$i" != "100" ]
do
i=$(($i+1))
sum=$(($sum+$i))
done
echo "The result of "1+2+3..+100" is ==> $sum"
或者用until
#!/bin/bash
#The program will use loop to calculate "1+2+3+...+100"
i=0
sum=0
until [ "$i" == "100" ]
do
i=$(($i+1))
sum=$(($sum+$i))
done
echo "The result of '1+2+3+...+100' is ==> $sum."
执行结果都是:
The result of 1+2+3..+100 is ==> 5050
O(∩_∩)O~,很好玩吧!