while conditional statement

while conditional statement (when the condition is met, it is always looping, suitable for daemon process, endless loop, while reads the entire line, for meets a space and starts another line)

Syntax
while conditional
do
command
done

Case:
Record the system load every 2 seconds

while true; do 也可以写成 while :;do

#!/bin/bash
while true
 do
 uptime
 sleep 2
done

Note: while true means that the condition is always true, so it will loop forever, like an endless loop, we call it a daemon

Use while to write a script 1+…100 sum

#!/bin/bash
sum=0
i=1
while ((i<=100))
  do
  ((sum=sum+i))
  ((i++))
done
 echo "sum=$sum"

If the number of this algorithm is very large, the calculation effect is very slow. It is recommended to use the summation formula ((sum=100*(100+1)/2)) echo $sum
is added to 1000000. Time can be compared to
time./ while2.sh
sum=500000500000

real 0m7.463s
user 0m7.191s
sys 0m0.272s
#!/bin/bash
i=1000000
((sum=1000000*(1000000+1)/2))
echo $sum

time ./sum.sh
500000500000

real 0m0.004s
user 0m0.002s
sys 0m0.000s

while read the file usage:
format:
while read line;do #read each line of the file through the read command and store it in the line variable
……….
#execute process done </file path to be imported

Case: Count the total number of bytes accessed by each file in all lines in the access_apache.log log

#!/bin/bash
sum=0
while read line                   #用read读入每一行
  do
  size=`echo $line|awk '{print $10}'`
  [ "$size" == "-" ] && continue      #结束本次循环继续下面循环
  ((sum=sum+$size))
done<access_apache.log           #放在done后面可以读入文件         
[  -n "$size" ] && echo "$sum"

Guess you like

Origin blog.csdn.net/bjgaocp/article/details/110220917