Bash脚本循环过早退出If语句

时间:2018-03-06 20:00:59

标签: linux bash shell service scripting

我的环境中的linux盒子上有一个脚本来循环一系列应该一直运行的服务,如果没有运行,请给我发一封电子邮件。

现在,除了两个问题外,似乎工作正常。我真的很感激一些帮助和见解。我的大多数背景来自Python和Powershell。

  1. 每当脚本检测到服务已关闭时,它将退出脚本,而不是循环其余部分。然后它将未检查的服务附加到电子邮件正文中,尽管我没有在mail命令中指定电子邮件正文。
  2. 经常会在“hostservices”上抛出错误的错误;而且我不知道如何去弄清楚原因。
  3. 脚本是每10分钟运行一次的cron作业。下面是脚本和服务列表的全文,以及脚本发现服务失效时会发生什么情况的屏幕截图。

    脚本

    #!/bin/bash
    
    while read services; do
    
        #Run Command to get Service Status, store results as string variable
        service_status=$(service $services status)
    
        #Check if the service is NOT running.
        if [[ "$service_status" != *"is running..." ]];
        then
                mail -s "Service $services is down on [SERVER]" [EMAIL ADDRESS]
        elif [[ $service_status == *"is running..." ]];
        then
                :
        else
                mail -s "ERROR IN SCRIPT, unable to get $services status on [SERVER]" [EMAIL ADDRESS]
        fi
    done < /home/services.txt
    

    services.txt的

    hostcontect
    hostservices
    ecs-ec
    ecs-ep
    imq
    tomcat
    httpd
    

    停机服务的电子邮件提醒

    SUBJECT: "Service hostservices is down on [SERVER]"
    BODY:
    ecs-ec
    ecs-ep
    imq
    tomcat
    httpd
    

1 个答案:

答案 0 :(得分:2)

mail从标准输入中读取电子邮件的正文。在您的情况下,输入文件被重定向到stdin,因此它会被读取。告诉邮件从其他地方读取身体,例如

mail -s ... < /dev/null
相关问题