# shell
循环跳出的break/continue
命令
# break命令
当满足某个条件时,有时会希望终止循环,shell
和大多数变成语言一样支持break/continue
命令,其使用方法:
#!/bin/bash
for (( a=1; a<=10; a++ ))
do
echo "value a $a"
for((b=1; b<=10; b++ ))
do
echo " value b $b"
if [ $b -eq 4 ]; then
echo " break"
break 2
fi
done
done
# break
# value 1
# value 2
# value 3
# value 4
值得注意的是break
默认是跳出当前层的循环,而与其他大多数语言不同的是shell
的break
命令还支持break n
参数,n
表示跳出几层循环,默认为1
。
#!/bin/bash
for (( a=1; a<=10; a++ ))
do
echo "value a $a"
for((b=1; b<=10; b++ ))
do
echo " value b $b"
if [ $b -eq 4 ]; then
echo " break"
break 2
fi
done
done
# value a 1
# value b 1
# value b 2
# value b 3
# value b 4
# break
如上,break
会直接结束循环。在while
和until
循环中同样支持break
命令。
# continue命令
continue
命令可以提前中止某次循环中的命令,但并不会完全终止整个循环。
#!/bin/bash
for (( v=1; v<=10; v++ ))
do
if [ $v -gt 5 ] && [ $v -lt 8 ]; then
continue
fi
echo "Iteration: $v"
done
# Iteration: 1
# Iteration: 2
# Iteration: 3
# Iteration: 4
# Iteration: 5
# Iteration: 8
# Iteration: 9
# Iteration: 10
也可以在 while
和 until
循环中使用 continue
命令,但要特别小心。记住,当shell
执行continue
命令时,它会跳过剩余的命令。
和 break
命令一样, continue
命令也允许通过命令行参数指定要继续执行哪一级循环continue n
。
#!/bin/bash
for (( a = 1; a <= 5; a++ ))
do
echo "Iteration $a:"
for (( b = 1; b < 3; b++ ))
do
if [ $a -gt 2 ] && [ $a -lt 4 ]; then
continue 2
fi
var3=$[ $a * $b ]
echo " The result of of $a * $b is $var3"
done
done
# Iteration 1:
# The result of of 1 * 1 is 1
# The result of of 1 * 2 is 2
# Iteration 2:
# The result of of 2 * 1 is 2
# The result of of 2 * 2 is 4
# Iteration 3:
# Iteration 4:
# The result of of 4 * 1 is 4
# The result of of 4 * 2 is 8
# Iteration 5:
# The result of of 5 * 1 is 5
# The result of of 5 * 2 is 10
# trick
在上面的命令中使用重定向,可以将循环中命令的结果保存到文件中。
#!/bin/bash
for (( a = 1; a <= 5; a++ ))
do
echo "Iteration $a:"
for (( b = 1; b < 3; b++ ))
do
if [ $a -gt 2 ] && [ $a -lt 4 ]; then
continue 2
fi
var3=$[ $a * $b ]
echo " The result of of $a * $b is $var3"
done
done > out.txt
还可以使用管道命令将循环的结果传递给别的命令,
#!/bin/bash
for (( a = 1; a <= 5; a++ ))
do
echo "Iteration $a:"
for (( b = 1; b < 3; b++ ))
do
if [ $a -gt 2 ] && [ $a -lt 4 ]; then
continue 2
fi
var3=$[ $a * $b ]
echo " The result of of $a * $b is $var3"
done
done | sort