break continue exit return 的区别

本文通过几个示例展示了Shell脚本中如何使用break、continue和exit来控制循环流程。包括了基本用法及其区别,例如break用于立即终止循环,而continue则跳过当前循环中的剩余部分并进入下一次迭代。

[root@localhost day1]# cat ss.sh 

#!/bin/bash


for ((i=0;i<5;i++))

do
if [ $i -eq 3 ]
then
break
#continue
#exit

#return

fii
echo $i;sleep 1
done
echo "ok"

###################################################

[root@localhost day1]# sh ss.sh           #由此看出break是直接终断循环的
0
1
2
ok

——————————————————————————————

[root@localhost day1]# sh ss.sh           #continue效果 还是中断当前循环,继续进行下一循环
0
1
2
4
ok

——————————————————————————————

[root@localhost day1]# sh ss.sh           #exit 直接退出了脚本
0
1
2

return :return must be function 

1.中断循环

2.返回值

[root@localhost day1]# sh return.sh
0
1
2
return.sh: line 12: return: can only `return' from a function or sourced script    #必须是函数
3
4
ok

 

#!/bin/bash

fuction_return (){              #加入函数
for ((i=0;i<5;i++))

do
if [ $i -eq 3 ]
then
#break
#continue
#exit
return
fi
echo $i;sleep 1
done
echo "ok"
}
fuction_return

[root@localhost day1]# sh return.sh               #结果
0
1
2

 

转载于:https://www.cnblogs.com/sxgaofeng/p/9174413.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值