如果语句过早退出Bash脚本循环

问题描述 投票:0回答:1

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

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

  1. 只要脚本检测到服务已关闭,它就会退出脚本,而不是遍历其余部分。然后,它将未检查的服务附加到电子邮件正文,尽管我没有在mail命令中指定电子邮件正文。
  2. 它经常会在“主机服务”上抛出错误的错误;我不知道怎么去弄清楚原因。

该脚本是每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
linux bash shell service scripting
1个回答
2
投票

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

mail -s ... < /dev/null
© www.soinside.com 2019 - 2024. All rights reserved.