Shell 循环语句

shell 循环语句

while 循环

while 循环可以嵌套,语法如下

1
2
3
4
5
6
7
8
9
10
11
while command1 ; # this is loop1, the outer loop
do
Statement(s) to be executed if command1 is true

while command2 ; # this is loop2, the inner loop
do
Statement(s) to be executed if command2 is true
done

Statement(s) to be executed if command1 is true
done

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/bin/sh

a=0
while [ "$a" -lt 10 ] # this is loop1
do
b="$a"
while [ "$b" -ge 0 ] # this is loop2
do
echo -n "$b "
b=`expr $b - 1`
done
echo
a=`expr $a + 1`
done

break/continue

语法

1
2
3
4
5
break       #跳出当前循环
break n #跳出多重循环

continue #当前循环 continue
continue n #n指定的外层循环 continue

跳出当前循环

1
2
3
4
5
6
7
8
9
10
11
12
13
#!/bin/sh

a=0

while [ $a -lt 10 ]
do
echo $a
if [ $a -eq 5 ]
then
break
fi
a=`expr $a + 1`
done

跳出外层循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/bin/sh

for var1 in 1 2 3
do
for var2 in 0 5
do
if [ $var1 -eq 2 -a $var2 -eq 0 ]
then
break 2
else
echo "$var1 $var2"
fi
done
done

for 循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/bin/sh

NUMS="1 2 3 4 5 6 7"

for NUM in $NUMS
do
Q=`expr $NUM % 2`
if [ $Q -eq 0 ]
then
echo "Number is an even number!!"
continue
fi
echo "Found odd number"
done

until 循环

1
2
3
4
5
6
7
8
9
#!/bin/sh

a=10

until [ $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done

Shell 循环语句
https://yxibng.github.io/2022/02/25/Shell/2022-02-25-shell 循环语句/
作者
yxibng
发布于
2022年2月25日
许可协议