if 逻辑判断

2016-10-09

if 逻辑判断

(1)不带 else

 格式如下:

  if 判断语句;then
   command
  fi

 例:

[root@133 ~]# vim if1.sh
#!/bin/bash

read -p "Please input your score:" a
if ((a<60));then
    echo "You didn't pass the exam."
fi

  在该脚本中,出现了 ((a<60)) 这样的形式,这是 shell 脚本中特有的格式,它等价于 if [$a -lt 60],用一个小括号或不用都会报错,请记住这个格式。执行结果:

[root@133 ~]# sh if1.sh
Please input your score:90
[root@133 ~]# sh if1.sh
Please input your score:33
You didn't pass the exam.

(2)带有 else

 格式如下:

  if 判断语句;then
   command
  else
   command
  fi

 例:

[root@133 ~]# vim if2.sh
#!/bin/bash

read -p "Please input your score:" a
if ((a<60));then
    echo "You didn't pass the exam."
else
    echo "Good! You passed the exam."
fi

 执行结果:

[root@133 ~]# sh if2.sh
Please input your score:80
Good! You passed the exam.

[root@133 ~]# sh if2.sh
Please input your score:45
You didn't pass the exam.

  和上一例唯一区别的地方是,如果输入大于等于 60 的数字会有提示。

(3)带有 elif

 格式如下:

  if 判断语句一;then
   command
  elif 判断语句二;then
   command
  else
   command
  fi

 例:

[root@133 ~]# vim if3.sh
#!/bin/bash

read -p "Please input your score:" a
if ((a<60));then
   echo "You didn't pass the exam."
elif ((a>=60))&&((a<85));then
   echo "Good!You pass the exam."
else
   echo "Very good! Your score is very high!"
fi

 这里的&&表示 并且 的意思,当然也可以使用 || 表示 或者 ,执行结果:

[root@133 ~]# sh if3.sh
Please input your score:90
Very good! Your score is very high!
[root@133 ~]# sh if3.sh
Please input your score:60
Good!You pass the exam.

  以上只是简单的介绍了 if 语句的结构。在数值大小判断中除了可以用(())的形式,还可以用“[ ]”的形式,但是就不能使用 >,<,= 这样的符合了,要使用 -lt (小于),-gt(大于),-le(小于等于),-ge(大于等于),-eq(等于),-ne(不等于)。下面就以命令行的形式简单比较一下,不再写 shell 脚本。

[root@133 ~]# a=10;if [ $a -lt 5 ];then echo ok;fi
[root@133 ~]# a=10;if [ $a -gt 5 ];then echo ok;fi
ok
[root@133 ~]# a=10;if [ $a -ge 10 ];then echo ok;fi
ok
[root@133 ~]# a=10;if [ $a -eq 10 ];then echo ok;fi
ok
[root@133 ~]# a=10;if [ $a -ne 10 ];then echo ok;fi

 注意:if 和“[”之间,“[”右边,“]”的左边都要有空格!

  再看看 if 中使用&&和 || 的情况

[root@133 ~]# a=10;if [ $a -lt 1 ]||[ $a -gt 5 ];then echo ok;fi
ok

[root@133 ~]# a=10;if [ $a -gt 1 ]||[ $a -lt 10 ];then echo ok;fi
ok

[root@133 ~]# a=10;if [ $a -gt 1 ]&&[ $a -lt 10 ];then echo ok;fi

标题:if 逻辑判断
作者:散宜生
地址:https://17kblog.com/articles/2016/10/09/1475975664856.html