Shell之while循环

While循环的格式:

while expression
do
command
command
、、、

done

1、计数器控制的while循环:
主要用于已经准确知道要输入的数据和字符串的数目。

例子:

#!/bin/bash
int=1
while (($int <=5 ))
do
echo $int
let "int++"
done

2、结束标记控制的while循环
主要用于不知道读入数据的个数,但是可以设置一个特殊的数据值来结束循环,该特殊值称为结束标记,通过提示用户输入进行操作。

例子:

#!/bin/bash
#用脚本演示使用结束标记控制while循环实现猜1~10内的数
echo "Please input the num (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 big,Try again.."
  read num
else
  exit 0
fi
done
echo "Yes,you are right !!"   

3、标志控制的while循环
用户输入标志值来控制循环的结束

例子:

#!/bin/bash
echo "Please input the num: "
read num
sum=0
i=1
signal=0
#while [[ $signal != 1 ]]
while (($signal != 1))
do
if [ $i -eq $num ];then
  let "signal=1"
  let "sum+=i"
  echo "1+2、、、+$num=$sum"
else
  let "sum=sum+i"
  let "i++"
fi
done

4、命令行控制的while循环
例子:

#!/bin/bash
echo "Please iput arguements is $# "
echo "What you input : "
while [[ $* != "" ]]
do
echo $1
shift
done
原文地址:https://www.cnblogs.com/Richardzhu/p/4236069.html