20.10 for Loop
- Syntax: for variable name in condition; Do ...; Done
;案例1[[email protected] shell]# cat for.sh#!/bin/bashsum=0for i in `seq 1 100`do sum=$[$sum+$i]doneecho $sum#输出的结果[[email protected] shell]# sh for.sh 5050
[[email protected] shell]# cat for2.sh #!/bin/bashcd /etc/for a in `ls /etc/`do if [ -d $a ] then ls -d $a fidone#for循环是以空格、回车符作为分割符分割。
20.11-20.12 while loop
- syntax while condition; Do ...; Done
;案例1[[email protected] shell]# cat while.sh #!/bin/bashwhile :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 30done;案例2[[email protected] shell]# cat while2.sh #!/bin/bashwhile :do read -p "Please input a number:" n if [ -z "$n" ] then echo "You did not enter the number." continue fi n1=`echo $n|sed ‘s/[0-9]//g‘` if [ ! -z "$n1" ] then echo "You can only enter a pure number." continue fi breakdoneecho $n
20.13 break jump out of the loop
[[email protected] shell]# cat break.sh #!/bin/bashfor i in `seq 1 5`do echo $i if [ $i -eq 3 ] then break fi echo $idoneecho aaaaaa
20.14 continue ends this cycle
[[email protected] shell]# cat continue.sh #!/bin/bashfor i in `seq 1 5`do echo $i if [ $i -eq 3 ] then continue fi echo $idoneecho $i
20.15 exit exits the entire script
[[email protected] shell]# cat exit.sh #!/bin/bashfor i in `seq 1 5`do echo $i if [ $i -eq 3 ] then exit fi echo $idoneecho $i
Shell script for loop, break out loop, continue end this loop