格式:if list; then list; [ elif list; then list; ] ... [ else list; ] fi


4.1.1 单分支

if 条件表达式; then
    命令
fi
#!/bin/bash 
N=10
if [ $N -gt 5 ]; then 
    echo yes
fi
# bash test.sh 
yes

4.1.2 双分支

if 条件表达式; then
    命令
else
    命令
fi
#!/bin/bash 
N=10
if [ $N -lt 5 ]; then 
    echo yes
else
    echo no
fi
# bash test.sh 
no
#!/bin/bash 
NAME=crond
NUM=$(ps -ef |grep $NAME |grep -vc grep) 
if [ $NUM -eq 1 ]; then
    echo "$NAME running."
else
    echo "$NAME is not running!"
fi
#!/bin/bash
if ping -c 1 192.168.1.1 >/dev/null; then 
    echo "OK."
else
    echo "NO!"
fi

if 语句可以直接对命令状态进行判断,就省去了获取$?这一步!

4.1.3 多分支

if 条件表达式; then 
    命令
elif 条件表达式; then 
    命令
else
    命令
fi

当不确定条件符合哪一个时,就可以把已知条件判断写出来,做相应的处理。

#!/bin/bash 
N=$1
if [ $N -eq 3 ]; then 
    echo "eq 3"
elif [ $N -eq 5 ]; then 
    echo "eq 5"
elif [ $N -eq 8 ]; then 
    echo "eq 8"
else
    echo "no"
fi

如果第一个条件符合就不再向下匹配。

#!/bin/bash
if [ -e /etc/redhat-release ]; then 
    yum install wget -y
elif [ $(cat /etc/issue |cut -d' ' -f1) == "Ubuntu" ]; then 
    apt-get install wget -y
else
    Operating system does not support. 
    exit
fi