在shell控制流程中,循环有三种,分别是for、while、until。另外在循环中打断和跳过的控制有:break、continue,
下面将分别介绍。
一、for
1、for的基本格式是
for name in list
do
statements
done
当list为$@时,in list 可以直接省略。
2、实例如下:
#!/usr/bin/env bash
forFunc1(){
for i in $@
do
if [ $i = one ]
then
echo "forFunc1 $i is one"
elif [ $i != two ]
then
echo "forFunc1 $i != two"
elif [ $i > one ]
then
echo "forFunc1 $i > one"
fi
done
}
forFunc1 one two three
forFunc2(){
for i
do
echo "forFunc2 input $i"
done
}
forFunc2 1 2 3
运行结果:
forFunc1 one is one
forFunc1 two > one
forFunc1 three != two
forFunc2 input 1
forFunc2 input 2
forFunc2 input 3
二、while
1、while的基本格式
while condition
do
statements
done
当condition为真时,循环体执行
2、实例如下:
#!/usr/bin/env bash
whileFunc(){
local i=0
while [ $i -lt 3 ]
do
if [ $i -eq 2 ]
then
break
fi
echo "whileFunc $i"
let "i+=1"
done
}
whileFunc
运行结果:
whileFunc 0
whileFunc 1
三、until
1、until基本格式
until condition
do
statements
done
当condition为假时,循环体执行
2、实例
#!/usr/bin/env bash
untilFunc(){
local i=4
until [ $i -lt 1 ]
do
let "i-=1"
if [ $i -eq 2 ]
then
continue
fi
echo "untilFunc $i"
done
}
untilFunc
运行结果:
untilFunc 3
untilFunc 1
untilFunc 0
四、break和continue
1、break
break指跳出当前循环,循环层数大于1时,可指定跳出几层循环,如 break 2
2、continue
continue指跳到下一次循环,循环层数大于1时,可指定跳出几层的下一次循环,如 continue 2