简体   繁体   English

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

[英]Bash Script Loop Exiting Prematurely on If Statement

I have a script on a linux box in my environment to loop through a series of services that should always be running, and if one isn't running, send me an email. 我在我的环境中的linux机器上有一个脚本,用于循环应始终运行的一系列服务,如果其中一个未运行,请给我发送电子邮件。

Now, it seems to work fine except for two issues. 现在,除了两个问题外,它似乎工作正常。 I'd really appreciate some help and insight. 我非常感谢您的帮助和见解。 Most of my background comes from Python and Powershell. 我的大部分背景来自Python和Powershell。

  1. Whenever the script detects a service that's down, it exits the script, instead of looping through the rest. 每当脚本检测到服务中断时,它都会退出脚本,而不是循环浏览其余的服务。 It then appends the services it didn't check to the body of the email, despite me not specifying an email body in the mail command. 然后,尽管我未在mail命令中指定电子邮件正文,但它将未检查的服务附加到电子邮件正文中。
  2. Every so often, it throws a false error on "hostservices"; 每隔一段时间,它会在“ hostservices”上引发错误的错误; and I have no idea how to even go about figuring out why. 我什至不知道该怎么做。

The script is a cron job running every 10 minutes. 该脚本是每10分钟运行一次的cron作业。 Full text of the script and list of services are below, as well as a screenshot of what happens when the script finds a service that's down. 下面是该脚本的全文和服务列表,以及该脚本发现已关闭的服务时发生的屏幕截图。

Script 脚本

#!/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 services.txt

hostcontect
hostservices
ecs-ec
ecs-ep
imq
tomcat
httpd

Email Alert for Down Service 停机服务的电子邮件警报

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

mail reads the body of the email from standard input. mail从标准输入中读取mail的正文。 In your case, the input file is redirected to stdin, so it's read instead. 在您的情况下,输入文件将重定向到stdin,因此将其读取。 Tell mail to read the body from elsewhere, eg 告诉邮件从其他地方读取身体,例如

mail -s ... < /dev/null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM