[root@localhost shell_project]# ps -aux | grep httpd | grep -v grep

[root@localhost shell_project]#
[root@localhost shell_project]# service httpd start
[root@localhost shell_project]# ps -aux | grep httpd | grep -v grep
root 4012 8.2 1.7 488316 17468 ? Ss 16:50 0:00 /usr/sbin/httpd -DFOREGROUND
apache 4013 0.0 0.8 488316 8620 ? S 16:50 0:00 /usr/sbin/httpd -DFOREGROUND
apache 4014 0.0 0.8 488316 8620 ? S 16:50 0:00 /usr/sbin/httpd -DFOREGROUND
apache 4015 0.0 0.8 488316 8620 ? S 16:50 0:00 /usr/sbin/httpd -DFOREGROUND
apache 4016 0.0 0.8 488316 8620 ? S 16:50 0:00 /usr/sbin/httpd -DFOREGROUND
apache 4017 0.0 0.8 488316 8620 ? S 16:50 0:00 /usr/sbin/httpd -DFOREGROUND

[root@localhost shell_project]# vim info-apache.sh

#!/bin/bash
#判断apcache是否启动
apcaches=$(ps -aux | grep httpd | grep -v grep)
if [ -n "$apcaches" ]
then
echo "$(date) 阿帕奇正常启动" >> /root/ap.log
else
echo $(service httpd start) &> /dev/null
echo "$(date) 阿帕奇异常" >> /root/ap_error.log
fi

shell脚本判断apcache是否启动(shell脚本学习笔记四)_bash

-n 就是判断字符串是否为空(空false 不空true)

[root@localhost shell_project]# bash ./info-apache.sh
[root@localhost shell_project]# cd
[root@localhost ~]# cat ap.log
2017年 08月 15日 星期二 17:04:18 CST 阿帕奇正常启动[root@localhost shell_project]# service httpd stop
Redirecting to /bin/systemctl stop httpd.service [root@localhost shell_project]# bash info-apache.sh

Redirecting to /bin/systemctl start httpd.service

[root@localhost shell_project]# ps -aux | grep httpd | grep -v grep

root 4172 1.7 1.7 488316 17464 ? Ss 17:13 0:00 /usr/sbin/httpd -DFOREGROUND

apache 4173 0.0 0.8 488316 8616 ? S 17:13 0:00 /usr/sbin/httpd -DFOREGROUND

apache 4174 0.0 0.8 488316 8616 ? S 17:13 0:00 /usr/sbin/httpd -DFOREGROUND

apache 4176 0.0 0.8 488316 8616 ? S 17:13 0:00 /usr/sbin/httpd -DFOREGROUND

apache 4177 0.0 0.8 488316 8616 ? S 17:13 0:00 /usr/sbin/httpd -DFOREGROUND

apache 4178 0.0 0.8 488316 8616 ? S 17:13 0:00 /usr/sbin/httpd -DFOREGROUND


然后你就自己去日志看吧
注意了,这个脚本有一个很大的缺陷,就是如果你有目录或者文件 是 httpd 起的名字,都会检测到,然后认为不为空执行成功。