while: while COMMANDS; do COMMANDS; done
在脚本中可以写成下列结构:
while CONDITION ; do
COMMANDS
done
while循环进入循环的条件:CONDITION逻辑判断结果为真;
while循环退出循环的条件:CONDITION逻辑判断结果为假;
until循环结构
until: until COMMANDS; do COMMANDS; done
在脚本中可以写成下列结构:
until CONDITION ; do
COMMANDS
done
until循环进入循环的条件:CONDITION逻辑判断结果为假;
until循环退出循环的条件:CONDITION逻辑判断结果为真;
注意:
1.while CONDITION 相当于 until ! CONDITION
2.while和until循环结构中,没有变量自增或自减的变化方法,因此需要使用语句手动给出变量的变化方式;
写一个脚本,使用while或until循环,计算100以内整数的和;
#!/bin/bash
#
#在$I=100的时候,退出循环,否则判断会进入101
declare -i I=0
until [ $I -eq 100 ] ; do
let I++
let SUM+=$I
done
echo $SUM
#!/bin/bash
#
declare -i I=0
while [ $I -lt 100 ] ; do
let I++
let SUM+=$I
done
echo $SUM
循环控制语句:
continue
continue: continue [n]
Resume for, while, or until loops.
提前结束第n层当前循环,直接进入下一轮条件判断,如果条件判断结果仍然满足循环进入条件,则开启下一轮循环;
break
break: break [n]
Exit for, while, or until loops.
提前结束第n层的循环,而且不再继续后续循环;
while和until的两种特殊循环使用方法:
1.无限循环方法:
while true ; do
COMMANDS
done
until false ; do
COMMANDS
done
猜数字游戏:
#!/bin/bash
#
NUMBER=$[RANDOM%100+1]
while true ; do
read -p "Input a number: " INPTNUM
if [ $INPTNUM -gt $NUMBER ] ; then
echo "Too big"
elif [ $INPTNUM -lt $NUMBER ] ; then
echo "Too small"
else
echo "Yes! you WIN. That's $NUMBER."
#在输入数字和随机数字匹配的时候,就退出
break
fi
done
#!/bin/bash
#
NUMBER=$[RANDOM%100+1]
until false ; do
read -p "Input a number: " INPTNUM
if [ $INPTNUM -gt $NUMBER ] ; then
echo "Too big"
elif [ $INPTNUM -lt $NUMBER ] ; then
echo "Too small"
else
echo "Yes! you WIN. That's $NUMBER."
break
fi
done
注意:在此类循环结构中,需要适当的添加continue或break控制语句,以使得无限循环可控;
2.实现遍历功能的while和until循环结构:
while read LINES ; do
COMMANDS
done < /PATH/FROM/SOMEFILE
until ! read LINES ; do
COMMANDS
done < /PATH/FROM/SOMEFILE
注意:在做遍历循环时,建议使用for;