linux之循环控制for、while、until命令详解

循环控制的命令主要有for、while,until命令用的也相对较少。

一、for命令
for命令的写法主要有以下两种格式:

格式1:
for i in {1..5}
do
        echo "this is $i"
done

格式2:
for((i=1;i<10;i++ ))
do
        echo "this is $i"
done

格式1是for 变量 in 序列,之前说过4中生成序列的方式在这里均可使用
传送门:linux之生成序列seq、{}等四种方式
格式2则类似于c语言的for命令的格式,之前也说过双括号(( ))中支持多个命令
传送门:linux之 、 [ ] 、 { }、[ ]、 []( )、 [ ] 、 [ ]、 [](( ))、[[ ]]、(( ))的作用

二、while命令
while命令的写法:

i=0
while [ $i -le 10 ]
do
        echo "this is $i"
        ((i++))
done

while命令后跟判断式,判断式返回值为真则继续循环,否则退出循环。判断式同样可以使用test、[ ]、[[ ]],与if的判断式用法一致。

三、until命令
until与while相反,当判断式的返回值为假时则继续循环,当判断式为真时则退出循环

i=0
while [ $i -le 10 ]
do
        echo "this is $i"
        ((i++))
done

四、continue和break

break是退出本层循环,继续执行本层循环体后面的代码,注意是退出本层循环体,如果是嵌套循环,则退出break所在层的循环,并非所有的循环

i=-1
while [ $i -lt 10 ]
do
        ((i++))
        if [ $i -eq 5 ];then
                break
        fi
        echo "this is $i"
done
echo "程序已经结束"

结果:
this is 0
this is 1
this is 2
this is 3
this is 4
程序已经结束

可见当$i为5时,直接跳出循环,执行循环体后面的echo语句。

continue则是跳过本次循环,不再执行continue下面的代码,回到循环判断式判断是否继续执行循环

i=-1
while [ $i -lt 10 ]
do
        ((i++))
        if [ $i -eq 5 ];then
                continue
        fi
        echo "this is $i"
done
echo "程序已经结束"

结果:
this is 0
this is 1
this is 2
this is 3
this is 4
this is 6
this is 7
this is 8
this is 9
this is 10
程序已经结束

可见结果没有打印this is 5,因为当$i为5时,跳过本次循环,不执行下面的echo语句,继续回到while判断。
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐