FreeSoftwareServers
FreeSoftwareServers

Reputation: 2791

Bash Logic Check - Repeating While Loop with nested "IF Then" statements

I'm writing a script to monitor my sip trunk and attempt to fix it. If it fails to fix the issue 6 times, then reboot the server. The script is called by cron via @reboot. I first had nested While Loops but that didn't work correctly so I switched to a never ending While Loop with two nested If Loops to perform the functions of the script.

I was wondering if somebody could take a quick look and see if the way I am attacking it makes sense and is logical approach.

Thank You,

Script as it stands:

#!/bin/bash

pwd="/srv/scripts"
count=0
echo "Script Started on $(date -u) Failure.Count=$count" >> "$pwd/failures.count"

start=start
while [ $start = "start" ]; do

sleep 420

var="$(asterisk -rx "pjsip show registrations" | grep -o Registered)"

    if [ "$var" != "Registered" ]; then
        amportal restart
        count=$(( $count + 1 ))
        echo "Trunk Failure on $(date -u) Failure.Count=$count" >> "$pwd/failures.count"
    fi

    if [ "$count" -gt 5 ]; then  
        echo "Server Reboot due to Failure.Count=$count on $(date -u)" >> "$pwd/reboot.notification"  
        reboot    
    fi
done

Upvotes: 0

Views: 49

Answers (1)

tripleee
tripleee

Reputation: 189427

There is no need to use a variable in the while loop, or to capture the grep output into a variable.

#!/bin/bash

pwd="/srv/scripts"
count=0
echo "Script Started on $(date -u) Failure.Count=$count" >> "$pwd/failures.count"

# No need for a variable here
while true; do
    # Fix indentation
    sleep 420

    # Again, no need for a variable; use grep -q
    if ! asterisk -rx "pjsip show registrations" | grep -q Registered
    then
        amportal restart
        count=$(( $count + 1 ))
        echo "Trunk Failure on $(date -u) Failure.Count=$count" >> "$pwd/failures.count"
    fi

    if [ "$count" -gt 5 ]; then  
        echo "Server Reboot due to Failure.Count=$count on $(date -u)" >> "$pwd/reboot.notification"  
        reboot    
    fi
done

I would perhaps also collect all the log notices in a single log file, and use a more traditional log format with a time stamp and the script's name bofore each message.

Should the counter reset to zero if you see a success? Having the server reboot because you disconnected the network cable at the wrong time seems like something you'd want to avoid.

Upvotes: 1

Related Questions