【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


posted @ 2018-03-31 21:41  追梦男生  阅读(812)  评论(0编辑  收藏  举报