Shell条件判断 双分支if语句

1
2
3
4
5
6
if [ 条件判断式 ]
then
条件成立时执行的程序
else
条件不成立时,执行的另一个程序
fi

实例:判断输入的路径是不是一个目录

1
2
3
4
5
6
7
8
9
#!/bin/bash
read -t 30 -p "Input a dir:" dir
if [ -d "$dir" ]
then
echo "Yes,yes yes"
else
echo "No,no,no"
fi

实例:判断apache服务是否启动

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/bin/bash
test=$(ps aux |grep httpd |grep -v grep)
#定义变量test 并且查找是否启动apache的结果赋值给test
#ps aux 查看当前所有正在运行的进程
#grep httpd 过滤出apache进程
#grep -v grep 排除自身进程
if [ -n "$test" ]
then
cho " $(date) httpd is ok " >> /tmp/autostart-acc.log
else
systemctl start httpd.service &>/dev/null
#centos7
echo " $(date) httpd is no \n httpd is autostart now" >> /tmp/autostart-err.log
fi