【Shell】Shell编程之while循环命令

语法结构

while命令的基本格式:
while test command
do
    other commands
done


计数器控制的While循环

示例1、打印小于等于10的数
[root@strong bash_stu]# cat test2.sh 
#!/bin/bash

i=1
while [ $i -lt 10 ]
do
  echo $i
  i=$(($i+1))
done
[root@strong bash_stu]# . test2.sh 
1
2
3
4
5
6
7
8
9
[root@strong bash_stu]# 
示例2、计算1~100内的奇数和
[root@strong shell_stu]# cat test.sh 
#!/bin/bash

sum=0
i=1

while [ $i -lt 100 ]
do
  sum=$(($sum+$i))
  i=$(($i+2))
done
echo "1+3+5+...+100="$sum
[root@strong shell_stu]# . test.sh 
1+3+5+...+100=2500
--或者
[root@strong shell_stu]# cat while.sh 
#!/bin/bash

sum=0
i=1

while ((i <= 100))
do
  let "sum+=i"
  let "i+=2"
done
echo "1+3+3+..."=$sum
[root@strong shell_stu]# . while.sh 
1+3+3+...=2500

结束标记控制的while循环

在Linux SHELL编程中,如果不指定读入数据的个数,可以设置一个特殊的数据值来结束while循环,该特殊数据值称为结束标志。其通过提示用户输入特殊字符或数字来操作,当用户输入该标记后结束while循环,执行done后的命令,while循环的形式如下:
read variable
while [[ "$variable"!=sentline1]]
do
     read variable
done

示例:
[root@strong ~]# cat while_01.sh 
#!/bin/bash

echo "Please enter a number(1~10)"

read num

while [[ "$num"!=4 ]]
do
  if [ "$num" -lt 4 ]
  then
     echo "Too small , try again"
     read num
  elif [ "$num" -gt 4 ]
  then
     echo "Too great, try again"
     read num
  else
    # exit 0
    break
  fi
done

echo "Congratulation ,you are right"
[root@strong ~]# . while_01.sh 
Please enter a number(1~10)
3
Too small , try again
5
Too great, try again
4
Congratulation ,you are right


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值