for loop
The syntax is as follows:
for variable in list
do
command
done
where variable
is the variable name to use, list
is the list to traverse, command
and is the command to execute.
For example, we can use a for loop to iterate over a list of numbers and perform the same operation on each number:
for i in 1 2 3 4 5
do
echo "Number: $i"
done
example
1. Calculate the sum of all integers from 1 to 100
2. Prompt the user to enter an integer less than 100, and calculate the sum of all integers from 1 to this number
3. There is a banana tree on the top of a certain mountain. A monkey picked several bananas from the tree on the first day, and immediately ate half of them. It was not satisfying, so he ate one more banana. The next day, the monkey ate half of the remaining bananas. Unable to resist the temptation, he ate another banana. And so on, eat half of the remaining bananas every day and then eat one more. On the tenth day, the monkey found that there was only one banana left. How many bananas did the monkey pick in total on the first day?
Reverse reasoning:
Day 10: 1 root
Day 9: (1+1)*2=4
Day 8: (4+1)*2=10
Day 7: (10+1)*2=22
Day 6: (22+1)*2=46
Day 5: (46+1)*2=94
Day 4: (94+1)*2=190
Day 3: (190+1)*2=382
Day 2: (382+1)*2=766
Day 1: (766+1)*2=1534
double for loop
Refers to the structure of a for loop nested inside another for loop
for ((variable=X; specify variable range; specify variable iteration mode))#define outer loop
do
for ((variable=y; specify variable range; specify variable iteration mode))#define inner loop
do
command sequence
to specify variable iterative way
done
command sequence
done
example
1. Isosceles triangle
2. Custom row number diamond
break statement
break [n] is used to break out of a single (n represents how many layers) layer loop
continue statement
continue is used to abort the operation in a loop, but it will not completely terminate the entire loop command
exit statement
exit is used to exit the script process and can customize the return value