One, for loop
Grammar one
for variable in value 1 value 2 value 3 ... do program done
Note: As long as there is "empty" between multiple values, not just spaces, line breaks, tabs, etc., for example, when reading a file, you can automatically traverse each line.
Example 1: Traversing certain items
#!/bin/bash for time in morning noon afternoon evening do echo "This time is $time !" done
Iterating over the values in a variable
#! / bin / bash #Unzip all tar.gz compressed packages in the lamp directory cd / lamp ls *. tar .gz> ls .log for i in $ ( cat ls .log) do tar -zxf $ i $> / dev / null done rm -rf / lamp / ls .log
Grammar 2
for ((initial value; loop control condition; variable change)) do program done
Note: The execution flow is: first run the "initial value" statement, then execute the loop body once, then execute the "variable change" statement, and then judge whether it meets the "loop control condition", if it does, continue execution, otherwise exit the for loop.
Examples:
#!/bin/bash s=0 for (( i=1;i<=100;i=i+1 )) do s=$(( $s+$i )) done echo "The sum of 1+2+...+100 is: $s"
Two, while loop
grammar:
while [conditional judgment] do program done
As long as the judgment formula holds, the loop will continue to run.
The order of execution is to first determine whether the "conditional judgment formula" is true. If it is true, the loop body is executed. After the execution, the "conditional judgment formula" is judged again, and so on, until the "conditional judgment formula" is not established.
Examples:
#!/bin/bash i=1 s=0 while [ $i -le 100 ] do s=$(( $s+$i )) i=$(( $i+1 )) done echo "The sum is: $s"
Three, until cycle
grammar:
until [condition judgment type] do program done
Contrary to the while loop, when the conditional judgment is established, the loop is exited.
The order of execution is to first determine whether the "conditional judgment formula" is true. If not, execute the loop body. After the execution, judge the "conditional judgment formula" again, and so on, until the "conditional judgment formula" is established.
Examples:
#!/bin/bash i=1 s=0 while [ $i -gt 100 ] do s=$(( $s+$i )) i=$(( $i+1 )) done echo "The sum is: $s"