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

Bash:如果尚未运行,则运行服务(Centos、Apache、Clam),bash,apache,centos,Bash,Apache,Centos,编写了一个简单的bash脚本,该脚本将运行以检查我的Centos服务器上是否正在运行httpd(apache)或clad(antivirus),如果没有,它将重新启动它们 #!/bin/bash if [[ ! "$(/sbin/service httpd status)" =~ "running" ]] then service httpd start elif [[ ! "$(/sbin/service clamd status)" =~ "running" ]] then

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

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

通过命令行对它进行了测试,这样它就可以工作了,但是有什么方法可以进一步优化它吗?

停止关注文本,只需检查返回值即可

#!/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 i.e. 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