判断就是根据不同的条件进行测试,进而根据不同的条件执行不同的语句,判断也就是设定语句的执行顺序。

1.if结构

if [ 条件判断式 ]
then
条件为真时,进行的操作
fi
或者
if [ 条件判断式 ];then
条件为真时,进行的操作
fi

[root@zhu1 shell]# sh if.sh
I'm working
###########
I'm working
[root@zhu1 shell]# cat if.sh
#!/bin/bash
if [ 33 -lt 55 ]
then
echo "I'm working"
fi
echo "###########"
if [ 33 -lt 55 ];then
echo "I'm working"
fi

2.if-else结构

简单的if结构仅仅满足if后面跟的表达式时才会执行then后面的指令,当不满足时不会有任何的操作,if-else结构是双向选择操作,当满足if后的条件时就执行then后的操作,当不满足时,就执行else后的操作。

if [  条件判断式 ];then
条件为真时,执行的操作
else
条件为假时,执行的操作
fi

[root@zhu1 shell]# sh if-else.sh
88 is less than 100
[root@zhu1 shell]# cat if-else.sh
#!/bin/bash
if [ 88 -lt 100 ];then
echo "88 is less than 100"
else
echo "88 is more than 100"
fi

3.if-elif-else结构

#if-else结构只能判断两个条件,当有三个或三个以上时需要使用if-else嵌套,然而嵌套有点麻烦,所以当多条件判断时通常使用if-elif-else结构

if [ 条件判断1 ];then
条件1为真时执行的指令
elif [ 条件判断2 ];then
条件2为真时执行的指令
elif [ 条件判断3 ];then
条件3为真时执行的指令
else
当前面的所有条件都不匹配时执行的指令
fi

[root@zhu1 shell]# sh if-elif-else.sh
please input a integer(0-100)
99
your score > 90
[root@zhu1 shell]# sh if-elif-else.sh
please input a integer(0-100)
88
your score >80
[root@zhu1 shell]# sh if-elif-else.sh
please input a integer(0-100)
77
your score >70
[root@zhu1 shell]# sh if-elif-else.sh
please input a integer(0-100)
55
your score <60
#执行的顺序是当第一个条件为假时则进行第二个,以此类推,直到满足条件便执行then后的命令,当都不满足时执行else后的命令;如果fi后有其他命令则会继续执行fi后的命令

4.case结构

case $变量 in
"value1")
指令;;
"value2")
指令;;
"value3")
指令;;
*)
指令;;
esac

[root@zhu1 shell]# sh case.sh
your name is zhu
[root@zhu1 shell]# cat case.sh
#!/bin/bash
name=zhu
case $name in
"zhu")
echo "your name is zhu";;
"jiang")
echo "your name is jiang";;
*)
echo "can you tell me your name";;
esac