Bash:运行服务,如果尚未运行(Centos,Apache,Clam)

写一个简单的bash脚本来运行,以检查我的Centos服务器上是否运行httpd(apache)或clamd(antivirus),如果没有,它将重新启动它们。

#!/bin/bash if [[ ! "$(/sbin/service httpd status)" =~ "running" ]] then service httpd start elif [[ ! "$(/sbin/service clamd status)" =~ "running" ]] then service clamd start fi 

testing它通过命令行,所以它的工作,但有什么办法进一步优化呢?

停止关心文本,只是检查返回值。

 #!/bin/sh service httpd status &> /dev/null || service httpd start service clamd status &> /dev/null || service clamd start 

或者只是不在乎,他们已经在运行,让系统处理它。

 #!/bin/sh service httpd start service clamd start 
 #!/usr/bin/env bash # First parameter is a comma-delimited string ie service1,service2,service3 SERVICES=$1 if [ $EUID -ne 0 ]; then if [ "$(id -u)" != "0" ]; then echo "root privileges are required" 1>&2 exit 1 fi exit 1 fi for service in ${SERVICES//,/ } do STATUS=$(service ${service} status | awk '{print $2}') if [ "${STATUS}" != "started" ]; then echo "${service} not started" #DO STUFF TO SERVICE HERE fi done