Shell Training Day8 8.22

while loop

? Syntax while condition; do…; done
? Case 1
#!/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

: means an endless loop, also Can be written as 1 or true

Get load

[[email protected] ~]# uptime|awk -F’load average: ”{print $2}’|cut -d. -f 1
0–Include spaces when specifying delimiters
[[emailprotected] ~]# uptime|awk -F’load average:”{print $2}’|cut -d.- f 1
0 returns more spaces and more spaces

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

#!/bin/bash
while :< br>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

continue–means continue above The loop

n1=echo $n|sed's/[0-9]//g' represents a purely numeric variable

break is also possible Used in a for loop

Out of the loop
#!/bin/bash
for i in seq 1 5
do
echo $i< br>if [$i == 3 ]
then
break
fi
echo $i
done
echo aaaaaaa

== compare strings, Numbers generally use eq

Why are they output twice? The first echo after –do prints a 1, and then judges that it is not equal to 3, and then prints again after fi

Usage of continue
End this cycle

# !/bin/bash
for i in seq 1 5
do
echo $i
if [$i == 3 ]
then
continue
fi
echo $i
done
echo $i

continue is to continue execution, and break is to start again

exit

< p>#!/bin/bash
for i in seq 1 5doecho $iif [$i == 3 ]thenexitfiecho $idoneecho aaaaaaa

< /p>

Leave a Comment

Your email address will not be published.