The basic syntax of the loop example bash shell

Foreword

Writing the bash shell loop statements are: for-in, for-i, while, until;

Cyclic interrupt control characters have: break, continue

Loop example

for-in

#! /bin/bash

for num in 1 22 14 55
do
        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

Results of the:

ps: for-in suitable to iterate, note array literal words, no parentheses, separated by a space, if it is a string, as a single value, with a space, note quotes.

for-i

Other languages, such as cyclic c / java in for (i = 0 ;;) or the like, a slightly different syntax, for example:

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

Results of the:

while

while loop termination expression can use logical expression: logic basic syntax of the bash shell expression

#! /bin/bash
#遍历当前目录,找到while.sh文件则结束遍历或全部遍历完毕,最后输出当前目录下的所有文件
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[*]}"

Results of the:

ps while the other is very simple, the format is:

while expression

do

    ....

done

until

while cycling conditions are: When this condition is satisfied, not satisfied until the end of the cycle has been out of the loop or condition, and until the contrary is, when this condition is not met, the cycle has been, until this condition is met:

#! /bin/bash

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

Results of the:

Cycle interrupt control

And c-language semantics, like, break out for the current cycle, continue to start the next round of the cycle, that is, behind the continue command is not executed.

#! /bin/bash

for i in `seq 10`
do
	echo "$i"
	# 如果i == 3,跳出循环
	[[ $i -eq 3 ]] && echo "i=3,break" && break
done
echo "循环结束,i的值是$i"
for i in `seq 5`
do
	# 如果 i == 2,不打印
	[[ $i -eq 2 ]] && echo "i=2, do not print" && continue
	echo "$i"
done

Results of the:

Published 136 original articles · won praise 81 · views 180 000 +

Guess you like

Origin blog.csdn.net/x763795151/article/details/97182679