当前位置:网站首页>"Forget to learn again" shell process control - 38. Introduction to while loop and until loop

"Forget to learn again" shell process control - 38. Introduction to while loop and until loop

2022-06-22 14:59:00 Flourishing

1、while loop

Yes while Circularly speaking , As long as the conditional judgment holds , The cycle goes on and on , Until the conditional judgment doesn't hold , The cycle stops . and for The second form of the loop for(( Initial value ; Cycle control conditions ; Variable change )) similar .

We write a 1 Add to 100 Example , Although this kind of example is of little help to system management , But it's very helpful to understand the loop :

while Cyclic syntax format :

while [  Conditional judgment  ]
    do
         Program 
    done

Example :1 Add to 100.

#!/bin/bash

#  To the variable i And variables s assignment 
#  from 1 Start adding 
i=1
#  Summation variables 
sum=0

#  perform while Circle sum 
#  If the variable i Is less than or equal to 100, Then execute the loop 
while [ $i -le 100 ]
    do
        sum=$(( $sum+$i ))
        i=$(( $i+1 ))
    done

#  Output summation result 
echo "The sum is:$sum"

explain :

while The cycle is Shell There are still very few scripts , Recycling main use for The first form of the loop for Variable in value 1 value 2 value 3 …, So we can understand it .

and while Loop in writing algorithm , It will be very convenient. .

2、until loop

until Circulation and while The cycle is reversed ,until As long as the conditional judgment does not hold, the loop will be carried out , And execute the loop program .

Once the cyclic condition is established , Then stop the cycle .

The grammar is as follows :

until [  Conditional judgment  ]
    do
         Program 
    done

Or write from 1 Add to 100 This example , Pay attention to and while Difference between cycles :

#!/bin/bash

#  To the variable i And variables s assignment 
#  from 1 Start adding 
i=1
#  Summation variables 
sum=0

#  perform while Circle sum 
#  If the variable i The value is greater than 100, Then execute the loop 
until [ $i -gt 100 ]
    do
        sum=$(( $sum+$i ))
        i=$(( $i+1 ))
    done

#  Output summation result 
echo "The sum is:$sum"

summary :

while Circulation and until Loops are especially easy to write as dead loops , Forgot to write variable changes in the loop body , Such as i=i+1 perhaps i++ etc. , The judgment conditions leading to the cycle always meet the conditions , The loop can't stop , Very expensive system resources .

原网站

版权声明
本文为[Flourishing]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221331232774.html