shell脚本学习之if条件判断

语句格式:

if(条件表达式)
  command
elif(条件表达式)
  command
else
  command
fi

if常见的判断逻辑运算符

-f: 判断文件是否存在,例如if[-f filename ]。
-d: 判断目录是否存在,例如if[ -d dir]。
-eq :等于,应用于整型比较,即equal.
-ne:不等于,应用于整型比较,即not equal。
-lt: 小于,应用于整型比较,即letter。
-gt:大于,应用于整型比较,即greater。
-le: 小于或等于,应用于整型比较。
-ge: 大于或等于,应用于整型比较。
-a:双方都成立(and) ,用法为逻辑表达式-a逻辑表达式
-o:单方成立(or),用法为逻辑表达式-o逻辑表达式。
-z:空字符串。
||:单方成立。
&&:双方都成立表达式。

实例:
使用if条件判断分数

#!/bin/bash
scores=$1
if [ $scores -eq 100 ]; then
   echo " very good!" ;
elif [ $scores -gt 85 ];then
   echo "good!" ;
elif [ $scores -gt 60 ];then
   echo " pass! " ;
elif [ $scores -lt 60 ]; then
   echo "no pass!";
fi

[root@jiangpeisi shell]# sh scores.sh 95
good!

判断网络主机状态

#!/bin/bash
ping -c2 -W1 $1 &>/dev/null
if [ $? -eq 0 ];then
  echo "$1 is UP"
else
  echo "$1

[root@jiangpeisi shell]# sh state.sh 192.168.32.2
192.168.32.2 is DOWN