一、if循环
语法格式如下:
单分支的if语句:
if condition
then
command1
command2
...
commandN
fi
双分支的if语句:
if condition
then
command1
command2
...
commandN
else
command
fi
多分支的if语句:
if condition1
then
command1
elif condition2
then
command2
else
commandN
fi
案例1:
if else单支循环可以直接在命令行组合运行
# if [ `awk -F: '/^root/ {print $3}' /etc/passwd` -eq 0 ];then ehco "true";fi
案例2:
双支循环判断当前shell环境
# vi chkshell.sh
#!/bin/bash
if [ $SHELL = "/bin/bash" ];then
echo "your shell is bash"
else
echo "your shell is not bash but $SHELL"
fi
案例3:
多支循环比较两个数的大小
# vi if1.sh
#!/bin/bash
a=10
b=20
if [ $a == $b ];then
echo "a is equal than b"
elif [ $a -gt $b ];then
echo "a is greater than b"
elif [ $a -lt $b ];then
echo "a is less than b"
else
echo "None of the condition met"
fi
二、for循环
格式:
for var in item1 item2 ... itemN
do
command1
command2
...
commandN
done
for ((expr1;expr2;expr3));do
command1
command2
...
commandN
done
案例1:
计算1到100的和
# vi for1.sh
#!/bin/bash
sum=0
for in in {1..100};do
let sum=$sum+$i
done
echo $sum
案例2:
计算1到100的和
# vi for2.sh
#!/bin/bash
sum=0
for((i=1;i ;;
*)
echo "usage:[start|stop|reload]"
;;
esac
# sh case1.sh start
service is running
案例2:
输入一个字符,判断该字符是字母、数字或是其他
# vi case2.sh
#!/bin/bash
read -p "press one key,then press return: " KEY
case $KEY in
[a-z]|[A-Z])
echo "It's a letter"
;;
[0-9])
echo "It's a digit"
;;
*)
echo "It's function keys,Spacebar other keys"
esac
六、跳出循环
在循环过程中,有时候需要在未达到循环结束条件时强制跳出循环,Shell使用两个命令来实现该功能:break和continue。
6.1、break语句
break命令允许跳出所有循环(终止执行后面的所有循环)。
案例1:
脚本进入死循环,直到输入的字符在1到5之外
# vi break1.sh
#!/bin/bash
while :
do
echo -n "please enter 1 to 5: "
read num
case $num in
1|2|3|4|5)
echo "your input number is $num"
;;
*)
echo "your number is error,over"
break
;;
esac
done
案例2:
数字到5跳出循环
# vi break2.sh
#!/bin/bash
i=1
while [ $i -lt 10 ];do
echo $i
if [ $i -eq 5 ]
then
break
fi
((i+=1))
done
执行结果就是输出
1
2
3
4
5
6.2、continue语句
continue命令与break命令类似,只有一点差别,它不会跳出所有循环,仅仅跳出当前循环。
# vi continue1.sh
#!/bin/bash
while :
do
echo -n "please enter 1 to 5: "
read num
case $num in
1|2|3|4|5)
echo "your input number is $num"
;;
*)
echo "your number is error"
continue
echo "over"
;;
esac
done
执行结果是,当输入1到5之外的字符时不会跳出循环,语句 echo "over" 不会执行。