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 :
whileThe cycle is Shell There are still very few scripts , Recycling main useforThe first form of the loopfor Variable in value 1 value 2 value 3 …, So we can understand it .and
whileLoop 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 :
whileCirculation anduntilLoops are especially easy to write as dead loops , Forgot to write variable changes in the loop body , Such asi=i+1perhapsi++etc. , The judgment conditions leading to the cycle always meet the conditions , The loop can't stop , Very expensive system resources .

![Front and back management system of dessert beverage store based on SSM framework dessert mall cake store [source code + database]](/img/1b/9060d58d4dbb7f6f3c3a58959b7f14.png)







