回圈 (loop)--while do done, until do done (不定回圈)

除了 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~,很好玩吧!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值