In Shell, there are various loop statements used to handle repetitive tasks, the most commonly used are for, while and until loops.
1. for loop statement
The for loop statement is used to perform the same operation on each element in a list, and its basic syntax is as follows:
for var in list
do
commands
done
In the above syntax, var is the loop variable, list is the list of elements to be traversed, and commands is the command block to be executed. For example:
#!/bin/bash
for i in 1 2 3 4
do
echo $i
done
array=("cherry" "apple" "banana" "orange")
for i in ${array[@]}
do
echo $i
done
output
1
2
3
4
cherry
apple
banana
orange
2.while loop statement
The while loop statement is used to repeatedly execute a set of commands until a condition becomes false (returns a non-zero value). Its basic syntax is as follows:
while condition
do
commands
done
In the above syntax, condition is the loop condition, and commands is the command block to be executed. For example:
#!/bin/bash
# 定义变量
counter=1
# while 循环
while [ $counter -le 5 ]
do
echo "Count: $counter"
((counter++))
done
# 循环结束
echo "Done!"
output
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Done!
3.until loop statement
The until loop is very similar to the while loop in shell scripting. A while loop repeatedly executes a block of code while this condition is true, while an until loop repeatedly executes a block of code while the condition is false. Here is a simple example of an until loop:
#!/bin/bash
# 定义变量
counter=1
# until 循环
until [ $counter -ge 10 ]
do
echo "Count: $counter"
((counter++))
done
# 循环结束
echo "Done!"
output
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Count: 6
Count: 7
Count: 8
Count: 9
Done!