Linux基础---流程控制语句

本文介绍了Linuxshell脚本中的流程控制语句,包括ifelse结构用于条件判断,for循环用于迭代操作,while循环执行直到条件不满足,以及break和continue语句对循环流程的控制。示例代码展示了如何在bash脚本中使用这些语句。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、啥是流程控制语句?

流程控制语句是用来控制程序中各语句执行顺序的语句。包括顺序结构、选择结构、循环结构。在各类程序语言中都少不了它的踪影。

2、流控语句的使用

下面使用vim编辑器来详细介绍流控语句的使用
(1)if else …fi
语法格式:

if 条件
then
	命令1
	命令2
	.....
else 
	命令1
	...
fiif 条件; then
	命令
else
	...
fi
[root@192 blog]# vim if.sh
[root@192 blog]# cat if.sh
#!/bin/bash
a=2
b=3
if ((a<b));then
	echo "a小于b"
else
	echo "a大于b"
fi
[root@192 blog]# bash if.sh
a小于b
[root@192 blog]# 

if else …if else …fi只需在中间继续加上条件即可,语法一样。
(2)for循环
语法格式:
for 变量 in item1 …itemN; do 命令1;命令2…done;

[root@192 blog]# vim for.sh
[root@192 blog]# cat for.sh
#!/bin/bash
for i in {1..5}
do
	echo "hello world $i "
done

[root@192 blog]# bash for.sh
hello world 1 
hello world 2 
hello world 3 
hello world 4 
hello world 5 
[root@192 blog]# 

例2:使用for循环批量新建文件和文件夹

for  i  in  {1..5}
do
	touch a$i
	mkdir b$i
done

(3)while语句
语法格式:

while 条件
do
	命令
done
[root@192 blog]# vim while.sh
[root@192 blog]# cat while.sh
#!/bin/bash
i=1
while (( $i<5 ))
do
	echo "$i"
	((i++))
done
[root@192 blog]# bash while.sh
1
2
3
4
[root@192 blog]# 

break、continue语句(while循环和for循环都适用噢)
break :命令允许跳出所有循环(终止执行后面的所有循环)

[root@192 blog]# vim while.sh
[root@192 blog]# cat while.sh
#!/bin/bash
i=1
while (( $i<5 ))
do
	echo "$i"
	((i++))
	if (( $i==3 ));then
	break
	fi
done
[root@192 blog]# bash while.sh
1
2
[root@192 blog]# 

continue:符合条件时仅仅跳出当前循环,再继续进行循环

[root@192 blog]# cat while.sh
#!/bin/bash
i=1
while (( $i<10 ))
do
	echo "$i"
	((i++))
	if (( $i==5 ));then
	echo "这是5"
	continue
	fi
done
[root@192 blog]# bash while.sh
1
2
3
4
这是5
5
6
7
8
9
[root@192 blog]# 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值