Bash script to monitor process and sendmail if failed

╄→гoц情女王★ 提交于 2019-12-01 00:46:57

So, one thing about your tests is that you're pushing the output to /dev/null, which means that VAL1 and VAL2 will always be empty.

Secondly, you don't need the elif. You have two basic conditions. Either things are running, or they are not. If anything is not running, send an email. You could do some additional testing to determine whether it's PROCESS TEST1 or PROCESS TEST2 that died, but that wouldn't strictly be necessary.

Here's how I might write a script to do the same thing.

#!/usr/bin/env bash

#Check if process is running
PID1=$(/usr/ucb/ps aux | grep "[P]ROCESS TEST1" | awk '{print $2}')
PID2=$(/usr/ucb/ps aux | grep "[P]ROCESS TEST2" | awk '{print $2}')

err=0

if [ "x$PID1" == "x" ]; then
        # PROCESS TEST1 died
        err=$(( err + 1 ))
else
        echo "$(date) - PROCESS TEST1 $VAL2 is Running" >> /var/tmp/Log.txt;
fi

if [ "x$PID2" == "x" ]; then
        # PROCESS TEST2 died
        err=$(( err + 2 ))
else
        echo "$(date) - PROCESS TEST2  is Running" >> /var/tmp/Log.txt;
fi

if (( $err > 0 )); then
        # identify which PROCESS TEST had the problem.
        if $(( err == 1 )); then
                condition="PROCESS TEST1 is down"
        elif (( $err == 2 )); then
                condition="PROCESS TEST2 is down"
        else
                condition="PROCESS TEST1 and PROCESS TEST2 are down"
        fi

        # let's send an email to get eyes on the issue, but we will restart the process after
        # we send the email.
        SUBJ="Process Error Detected"
        FROM="Server"
        TO="someone@acme.com"
        (
        cat <<-EOT
        To : ${TO}
        From : ${FROM}
        Subject : ${SUBJ}

        $condition at $(date) please login to the server to check that the processes were restarted successfully.

        EOT
        ) | sendmail -v ${TO}

        # we reached an error condition, and we sent mail
        # now let's restart the svc.
        /usr/sbin/svcadm restart Foo
fi

elseif ? do you mean elif ?

also you thought about using functions and putting the sendmail part within a function that gets called out from within the if statement?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!