shell 脚本-循环
shell 中的循环包括 for
while
until
三种
for
for
循环的语法格式为 for var in item1 item2 ... itemN do command1 command2 ... commandN done
str_arr=('a' 'b' 'c' 'd')
for item in ${str_arr[*]}
do
echo $item
done
输出结果:
a
b
c
d
还可以使用 for
循环输出字符串
str="I am eno"
for str in $str
do
echo $str
done
输出结果:
I
am
eno
while
while
的语法格式为 while condition do command1 command2 ... commandN done
当 condition
为 true
时, 继续执行循环体的内容, 直到condition
为 false
跳出循环
num=0
# num 小于等于5时循环递增, 直至 num 大于 5
while [ $num -le 5 ]
do
echo $num
num=`expr $num + 1`
done
输出结果:
0
1
2
3
4
5
until
until
的用法和 while
一样, 语法格式同样时 until condition do command1 command2 ... commandN done
. 不同的是, until
的执行条件和 while
相反. while
是 condition
为 true
执行, 而 until
则是 condition
为 false
时才执行.
num=10
# num 大于5时执行递减, 直至 num 小于等于 5
until [ $num -le 5 ]
do
echo $num
num=`expr $num - 1`
done
执行结果:
10
9
8
7
6
循环的中断
shell
中循环可以使用 break
或 continue
中断, 执行 break
会跳出当前所有循环
而 continue
则会跳出所有循环
num_list=(1 2 3 4 5 6 7 8 9)
for number in ${num_list[*]}
do
if [ $number -ge 5 ]
then
# 当 number 大于等于 5 时, 跳出所有循环, 不再遍历之后的数据
break
fi;
echo $number
done
执行结果:
1
2
3
4
num_list=(1 2 3 4 5 6 7 8 9)
# 输出所有偶数
for number in ${num_list[*]}
do
if [ `expr $number % 2` != 0 ]
then
# 当number为奇数时, 跳出当前循环不执行 echo $number 当时依旧会遍历之后的数据
continue
fi;
echo $number
done
执行结果:
2
4
6
8