1、啥是流程控制语句?
流程控制语句是用来控制程序中各语句执行顺序的语句。包括顺序结构、选择结构、循环结构。在各类程序语言中都少不了它的踪影。
2、流控语句的使用
下面使用vim编辑器来详细介绍流控语句的使用
(1)if else …fi
语法格式:
if 条件
then
命令1
命令2
.....
else
命令1
...
fi
或
if 条件; 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]#