跟我一起写Shell脚本之十---循环(1 while)

1、语法

while语法:当满足某个条件时,就进入循环

while [ 条件 ]
do
    xxx
done

until语法:当满足某个条件时,就退出循环

until [ 条件 ]
do
    xxx
done

2、例子1

我们计算1到n加起来的和,用while写脚本016_while.sh:

#!/bin/bash

if [ $# -ne 1 ]; then
echo "please input a parameter to caculate"
echo "For example: ./016_while.sh 100"
exit
fi

declare -i num=1

echo "We begin to caculate 1+...+$1"

declare -i total=0
while [ $num -le $1 ]
do
        total=$num+$total
        num=$num+1
done

echo "Final result is: "
echo $total

执行结果:

$ ./016_while.sh 100
We begin to caculate 1+...+100
Final result is: 
5050

3、例子2

我们计算1到n加起来的和,用until写脚本017_until.sh:

#!/bin/bash

if [ $# -ne 1 ]; then
echo "please input a parameter to caculate"
echo "For example: ./016_while.sh 100"
exit
fi

declare -i num=1

echo "We begin to caculate 1+...+$1"

declare -i total=0
until [ $num -gt $1 ]
do
        total=$num+$total
        num=$num+1
done

echo "Final result is: "
echo $total

可以看到,差别仅仅在于until那一行。

执行结果:

$ ./017_until.sh 100
We begin to caculate 1+...+100
Final result is: 
5050

好了,今天的部分就到这里了,接下来的Shell脚本之旅会更久精彩!

===================================================================================

注意:本文为本人原创,版权所属为个人所有,欢迎转载,但是转载请注明出处。

===================================================================================

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值