20.10 for cycle
Syntax: for variable name in condition; do... ; done
Case 1: Calculate the sum of 1 to 100
#!/bin/bash sum=0 for i in `seq 1 100` do sum=$[$sum+$i] echo $i done echo $sum
Case 2 (File List Loop):
#!/bin/bash cd /etc/ for a in `ls /etc/` do if [ -d $a ] then ls -d $a fi done
Note: for loops, spaces and carriage returns are used as separators
20.11 while cycle
Grammar: while condition; do... ; done
Case 1: View the system load for no more than 30 seconds and send more than 10 emails
#!/bin/bash while : //Represents a dead cycle do load=`w|head -1|awk -F 'load average: ' '{print $2}'|cut -d . -f1` if [ $load -gt10 ] then /usr/local/sbin/mail.py 125455@qq.com "load high" "$load" fi sleep 30 done
Case 2: Human Interactive Input of a Number in the Cycle
#!/bin/bash while : do read -p "please input a number:" n if [ -z "$n" ] then echo "You need to enter something" continue //Continue to execute previous orders fi n1=`echo $n|sed 's/[ 0-9 ]//g'` if [ ! -z "$n1" ] then echo "You can only enter a number." continue fi break //Exit loop done echo $n
20.13 break out of the loop
Case study:
#!/bin/bash for i in `seq 1 5` do echo $i if [ $i == 3 ] then break fi echo $i done echo aaaaa
The best way to compare numbers is to use eq
Comparing strings==
20.14 continue ends this cycle
Ignore the code under continue and go straight to the next loop
#!/bin/bash for i in `seq 1 5` do echo $i if [ $i == 3 ] then continue fi echo $i done echo aaaaa
Contrast:
continue
break
20.15 exit exits the entire script
#!/bin/bash for i in `seq 1 5` do echo $i if [ $i==3 ] then exit fi echo $i done echo aaaaa
Continue: End this cycle and continue it
break: Exit the entire cycle
exit: exit the entire script