sh脚本的流程控制不可为空,如else后如果没有需要执行的语句,则不要写else
1. if-else
# 适用于脚本形式
if condition
then
command1
command2
...
commandn
fi
# ---------------------
if condition1
then
command1
elif condition2
then
command2
else
commandn
fi
# 适用于命令行
if [ 数值计算 ]; then command; fi
注:
condition两边需用[]括起来
eg:
[root@k8s-master test6]# cat t0.sh
#!/bin/bash
n1=$[2+3]
n2=$[2*3]
if test $[n1] -eq $[n2]
then
echo "test $[n1] -eq $[n2]: true"
else
echo "test $[n1] -eq $[n2]: false"
fi
[root@k8s-master test6]# sh t0.sh
test 5 -eq 6: false
[root@k8s-master test6]#
2. for
格式:
# 适用于脚本形式
for var in item1 time2 ... itemN
do
command1
command2
...
commandN
done
# 适用于命令行形式
for var in item1 item2 ... itemN; do command1; command2... ; done
eg:
[root@k8s-master test6]# for var in 1 2 3 4 5; do echo "The value is: $var"; done
The value is: 1
The value is: 2
The value is: 3
The value is: 4
The value is: 5
[root@k8s-master test6]#
[root@k8s-master test6]# for str in 'hello world'; do echo "$str\n"; done
hello world\n
[root@k8s-master test6]#
3. while
格式:
while condition
do
command
done
eg:
[root@k8s-master test6]# ./t1.sh
1
2
3
4
5
[root@k8s-master test6]# cat t1.sh
#!/bin/bash
i=1
while (( $i <= 5))
do
echo $i
let i++
done
[root@k8s-master test6]#
[root@k8s-master test6]# ./t2.sh
ctrl+d to exit
your like actor:tom
actor: tom
jack
actor: jack
[root@k8s-master test6]# cat t2.sh
#!/bin/bash
echo 'ctrl+d to exit'
echo -n 'your like actor:'
while read actor
do
echo "actor: $actor"
done
[root@k8s-master test6]#
4. until
格式:
until condition
do
command
done
eg:
[root@k8s-master test6]# ./t3.sh
0
1
2
3
4
5
6
7
8
9
[root@k8s-master test6]# cat t3.sh
#!/bin/bash
i=0
until [ ! $i -lt 10 ]
do
echo $i
i=$[i+1]
done
[root@k8s-master test6]#
5. case
格式:
case val in
pattern1)
command1
command2
...
commandN
;;
pattern2)
command1
command2
...
commandN
;;
esac
eg:
[root@k8s-master test6]# ./t4.sh
input a num between 1-2:
3
input not 1 or 2
[root@k8s-master test6]# cat ./t4.sh
#!/bin/bash
echo 'input a num between 1-2:'
read n
case $n in
1) echo 'input 1'
;;
2) echo 'input 2'
;;
*)
echo 'input not 1 or 2'
;;
esac
[root@k8s-master test6]#
6. continue/break
[root@k8s-master test6]# ./t5.sh
input 1 or 2
1
input: 1
2
input: 2
3
not 1 or 2 break
[root@k8s-master test6]# cat t5.sh
#!/bin/bash
echo 'input 1 or 2'
while true
do
read n
if [ $n -ne 1 -a $n -ne 2 ]
then
echo 'not 1 or 2 break'
break
else
echo "input: $n"
fi
done
[root@k8s-master test6]#