【问题标题】:Bash: run service if not already running (Centos, Apache, Clam)Bash:如果尚未运行,则运行服务(Centos、Apache、Clam)
【发布时间】:2015-11-17 09:06:46
【问题描述】:

编写了一个简单的 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

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

【问题讨论】:

    标签: bash apache centos


    【解决方案1】:

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

    #!/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
    

    【讨论】:

      【解决方案2】:
      #!/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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-13
        • 1970-01-01
        • 2023-04-01
        • 2017-11-27
        • 2023-04-10
        • 2021-01-30
        • 1970-01-01
        • 2011-01-06
        相关资源
        最近更新 更多