Jade Fitzgerald
Jade Fitzgerald

Reputation: 13

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.

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.

  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.
  2. Every so often, it throws a false error on "hostservices"; and I have no idea how to even go about figuring out why.

The script is a cron job running every 10 minutes. 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

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

Upvotes: 0

Views: 105

Answers (1)

choroba
choroba

Reputation: 241818

mail reads the body of the email from standard input. In your case, the input file is redirected to stdin, so it's read instead. Tell mail to read the body from elsewhere, e.g.

mail -s ... < /dev/null

Upvotes: 2

Related Questions