if语句

1151人浏览 / 0人评论

if语句

1、if格式说明

if 条件表达式;then
	命令
fi

2、示例

[root@gmw-jump-server ~]# cat if.sh
#!/bin/bash
N=5
if [ $N -gt 3 ];then
	echo "${N}>3"
fi

3、else双分支(则)

[root@gmw-jump-server ~]# cat if-else.sh 
#!/bin/bash
N=5
if [ $N -gt 6 ];then
	echo "${N}>6"
  else
	echo "${N}<6"
fi

4、判断nginx进程是否存在

[root@777 ~]# cat nginx.sh 
#!/bin/bash
NUM=`ps -ef|grep nginx|grep -vc grep`
NAME=nginx
if [ $NUM -gt 1 ]; then
	echo "$NAME running"
else
	echo "$NAME is not running"
fi

5、简单检查主机存活

[root@gmw-jump-server ~]# cat 2.sh 
#!/bin/bash
ping -c 1 -w 2 10.0.12 >/dev/null
if [ $? -eq 0 ];then
	echo "ok"
else
	echo "NO"
fi

6、elif连续判断猜数字

[root@gmw-jump-server ~]# cat 2.sh 
#!/bin/bash
N=$1
if [[ $N == [1-3] ]];then
	echo "$N is 1-3"
elif [[ $N == [4-7] ]];then
	echo "$N is 4-7"
elif [[ $N == [8-9] ]];then
	echo "$N is 8-9"
else
	echo "$N not is 1-9"
fi

全部评论