for循环、while循环、break、continue、exit

1、 for循环

语法:for 变量名 in 条件; do …; done
案例1

#!/bin/bash
sum=0
for i in `seq 1 100`
do
# echo "$sum + $i"
sum=$[$sum+$i]
done
echo $sum

注意:for 在用于文件或目录列表的时候,它是以回车或空格为分隔符的(所以得注意文件名中不能有空格)。

对文件相关的应用:

 

2、while循环

#!/bin/bash
while :
do
load=`w|head -1|awk -F 'load average: ' '{print $2}'|cut -d. -f1`
if [ $load -gt 10 ]
then
top|mail -s "load is high: $load" [email protected]
fi
sleep 30
done

while  continue break  等相关:

#!/bin/bash
while :
do
read -p "Please input a number: " n
if [ -z "$n" ]
then
echo "you need input sth."
continue
fi
n1=`echo $n|sed 's/[0-9]//g'`
if [ -n "$n1" ]
then
echo "you just only input numbers."
continue
fi
break
done
echo $n

 

3、break 跳出当前循环体:

#!/bin/bash
for i in `seq 1 5`
do
echo $i
if [ $i == 4 ]
then
break
fi
echo $i
done
echo "循环结束"

 

4、continue :当脚本循环中遇到continue时,就继续从循环体 头部开始执行,

而continue后面的语句,这次就不再执行。

#!/bin/bash
for i in `seq 1 5`
do
echo $i
if [ $i == 4 ]
then
continue
fi
echo $i
done
echo "循环结束"


 

5、exit,直接退出整个脚本。

#!/bin/bash
for j in `seq 1 3`
do
for i in `seq 1 3`
do
if [ $i == 1 ];then
echo "这是第j=$j 次循环i==$i,运行continue看效果"
continue
fi
if [ $i == 2 ];then
echo "这是第j=$j 次循环i==$i,运行break 看效果"
break
fi
done
if [ $j == 3 ];then
echo "这是第j=$j 次循环j==$j,运行exit 看效果"
exit $j
fi
done


猜你喜欢

转载自www.cnblogs.com/nfyx/p/9333598.html