Issue in the shell script sending email

Viewed 53

I am trying to check a table and send email based on the number of records. If the records are zero for the particular date then success email shall go out. If there is any record for the particular day then error messages should go out. My problem is - the opposite is happening. even though there are no records, error mail is going out.

Below is the script


#!/bin/bash
export PGPASSWORD=xyz
TIMESTAMP=`date "+%Y-%m-%d %H:%M:%S"`
mailid='xyz@gmail.com'

cd /opt/postgres/pgsql/bin

vartest=`./psql -U user -h  host -p port umrm -t -c "select count(*) from dataprocess_errors where error_date = current_date"` >> /opt/rmapp/test_error.log

if [$vartest -eq 0]
then

echo 'Files processed without errors'  | mutt -s "Processing Success `date`" $mailid $attached  >> /opt/rmapp/test_error.log

else

error=`./psql -U user -h  host -p port umrm-t -c "select count (*) from dataprocess_errors where error_date = current_date and error_message like '%More than 25 employees%';"` >> /opt/rmapp/test_error.log

if [$error -eq 0]
        then

        echo 'Please check the table and fix the errorneous records'  | mutt -s "Alert!! $vartest records failed in processing  `date`" $mailid $attached  >> /opt/rmapp/test_error.log

        else

        echo 'Please check the table'  | mutt -s "Alert!!! processing stopped  `date`" $mailid $attached  >> /opt/rmapp/test_error.log
        fi

fi

echo "Error Check completed at :  $TIMESTAMP" >>  /opt/rmapp/test_error.log

the second if condition in the else section is to identify the different kind of errors based on the output of variable "error".

I am a noob in shell scripting so kindly help. Thanks in advance for all the help.

2 Answers

In your lines

vartest=`./psql -U rmdbprd -h  atla-db-rmgr-prd-priv.com -p 5432 umrm -t -c "select count(*) from dataprocess_errors where error_date = current_date"`

and

error=`./psql -U rmdbprd -h  atla-db-rmgr-prd-priv.com -p 5432 umrm-t -c "sele ........

you are getting the standard out from the command - not the error code

to get the error code you can (as an example):

./psql -U rmdbprd -h  atla-db-rmgr-prd-priv.com -p 5432 umrm -t -c "select count(*) from dataprocess_errors where error_date = current_date"
if [ $? -ne 0 ];
then
  echo "there was an error on above command"
fi

note: the if must follow directly after the command you are testing the error code on

REF: https://en.wikipedia.org/wiki/Bash_(Unix_shell)

Considering your psql command is working fine, you have only one issue in above script. In both if conditions space after '[' and before ']' is missing. So your if conditions should be like :

if [ $vartest -eq 0 ]

and

if [ $error -eq 0 ]
Related