preface

The loop statements in bash shell are for-in, for-i, while, until;

Loop interrupt control characters are: break, continue

Loop statement example

for-in

#! /bin/bash

for num in1 and 14 55do
        echo $num
done
echo "1 2 3 4 5 loop output"
for num in `seq 5`
do
        echo $num
done
echo "charactor string"
for str in hello world "hello, world"
do
        echo $str
done
Copy the code

Execution Result:

P.S. :for-in is suitable for traversing arrays of numbers. If the array literals are not parentheses, they are separated by Spaces. If the array literals are strings, they are used as a single value, with Spaces in between.

for-i

Other languages, such as C/Java for(I =0;;) The syntax is slightly different as shown in the following example:

#! /bin/bash
for ((i=0; i<3; i++))
do
        echo $i
done
Copy the code

Execution Result:

while

A termination expression for a while loop statement can use a logical expression: a logical expression of the bash shell’s basic syntax

#! /bin/bash
If you find the while.sh file, you will end the traversal or complete the traversal, and finally output all files in the current directory
files=(`ls`)
index=0
file="null"
while [[ -n $file && $file! ="while.sh" ]]
do
        file=${files[$index]}
        echo $file
        let index++
done
echo "all file: ${files[*]}"
Copy the code

Execution Result:

P.S. Other while are very simple, like this:

while expression

do

    ....

done
Copy the code

until

The loop condition of while is: when this condition is satisfied, the loop continues until the unsatisfied condition ends or breaks out of the loop, while until is the opposite: When this condition is not satisfied, the loop continues until the satisfied condition:

#! /bin/bash

i=0
until [ $i -gt 5 ]
do
	echo $i
	let i++
done
Copy the code

Execution Result:

Loop interrupt control

As semantically with C, break is used to break the current loop and continue to start the next loop, that is, the command after continue is not executed.

#! /bin/bash

for i in `seq 10`
do
	echo "$i"
	# If I == 3, break out of the loop
	[[ $i -eq 3 ]] && echo "i=3,break" && break
done
echo "End of loop, I is zero$i"
for i in `seq 5`
do
	# if I == 2, do not print
	[[ $i -eq 2 ]] && echo "i=2, do not print" && continue
	echo "$i"
done
Copy the code

Execution Result: