文章目录
- 五、循环语句
- 1、for 循环
- 1.1 带列表的for循环
- 1.2 不带列表的for循环
- 1.3 类C风格的for循环
- 2、while 循环
-
- 3、嵌套循环案例
五、循环语句
1、for 循环
for
循环是编程语句中非常常见的一种循环,以列表为范围遍历其中变量,进行运算或执行某些命令以达到某些要求;for
循环主要分为三种类型:带列表的for
循环、不带列表的for
循环、类C风格的for
循环;
1.1 带列表的for循环
for variable in {list}
do
statement1
statement2
...
done
此语法中,variable
称为循环变量,list
是一个列表,可以是一系列的数字或者字符串,元素直接使用空格间隔,do
和done
之家的语句称为循环体,即循环结果中重复执行的语句内容,for
循环的循环次数与list
元素的个数有关。
[root@localhost shell]
for IP in 192.168.1.101 192.168.1.102
do
echo $IP
done
[root@localhost shell]
192.168.1.1
192.168.1.2
192.168.1.3
192.168.1.4
192.168.1.5
192.168.1.6
192.168.1.7
192.168.1.8
192.168.1.9
192.168.1.10
1.2 不带列表的for循环
for variable
do
statement1
statement2
...
done
当循环代码块内不带list
列表时,需要在调用脚本时定义遍历内容,否则产生报错;
[root@localhost shell]
for IP
do
echo 192.168.1.$IP
done
[root@localhost shell]
192.168.1.1
192.168.1.2
192.168.1.3
192.168.1.4
192.168.1.5
192.168.1.6
192.168.1.7
192.168.1.8
192.168.1.9
192.168.1.10
1.3 类C风格的for循环
for ((expression1;expression2;expression3))
do
statement1;
statement2;
...
done
此代码块中通过不同的运算符定义了不同的变量范围区间,以此为列表进行遍历;
[root@localhost shell]
for ((i=1;i<=254;i++))
do
if ping -c 2 -w 1 192.168.1.$i &> /dev/null
then
echo "192.168.1.$i is up!!"
else
echo "192.168.1.$i is down!!"
fi
done
2、while 循环
while
循环是另外一种常见的循环结构,使用while
循环,可以使得用户重复执行一系列的操作,直到某个条件的发生。
while expression
do
statement1
statement2
done
2.1 循环体读取文件的三种方法
循环中若想引入文件内容,主要分为三种引入方法:采用exec
命令读取文件、采用cat
命令读取文件、采用输入重定向读取文件;
exec < file
while read line
do
statement
done
cat file | while read line
do
statement
done
while read line
do
statement
done < file
2.2 循环类型
while
循环主要用于重复循环,主要分为三种类型:随机数循环、until
循环、select
循环;
- 随机数循环:产生随机数,比较输入值与随机数的大小,相同则结束程序。
[root@localhost shell]
PRICE=$[$RANDOM % 100]
TIMES=0
while true
do
read -p "Please enter your number:" INT
let TIMES++
if [ $INT -eq $PRICE ]
then
echo "is lucking,you bingo it!"
echo "is $TIMES times!"
exit 100
elif [ $INT -gt $PRICE ]
then
echo "$INT is too high"
else
echo "$INT is too low"
fi
done
until expression
do
statement1
statement2
...
done
select 变量名 [ in 菜单值列表 ]
do
statement1
statement2
...
done
3、嵌套循环案例
- 打印9x9乘法表
[root@localhost shell]
for i in {1..9}
do
for j in {1..9}
do
[ $j -le $i ] && echo -n "$i*$j=`echo $(($i*$j))` "
done
echo " "
done
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)