Capturing and mailing bash script errors

流过昼夜 提交于 2019-12-23 17:33:45

问题


I have a script that I run nightly in cron to backup some postgres databases for several hosts on my network. I have a way of getting alerted that the script fails by leveraging the exit status, but it doesn't tell me WHY it failed.

Based off the following code, how can I capture any errors that occur when the script is run, and email them to me so I can have a better understanding of what happened.

FILEDATE=`date '+%Y-%m-%d'`
BASEDIR=/u1/$1/db_dumps
PGDUMP=/path/to/pg_dump
HOST=$1
DB=$2

if [ $DB == all ]
then 
    for ALLDUMPS in db1 db2 db3
        do
        ssh root@$HOST "env PGUSER=pguser PGPASSWORD=pgpassword $PGDUMP -Fc $ALLDUMPS" | pbzip2 > $BASEDIR/$FILEDATE-$HOST-$ALLDUMPS.dump.bz2
            if [ $? -ne 0 ]
                then mutt -s "dbdumper could not create a backup of $ALLDUMP from $HOST" me@myemail.com < /dev/null
            fi
        done

else 
    ssh root@$HOST "env PGUSER=pguser PGPASSWORD=pgpassword $PGDUMP -Fc $DB" | pbzip2 > $BASEDIR/$FILEDATE-$HOST-$DB.dump.bz2
if [ $? -ne 0 ]
    then mutt -s "dbdumper failed to create a backup of $DB from $HOST" me@myemail.com < /dev/null
fi
fi

回答1:


Capture stderr from the ssh command, and email that to yourself.

stderr=$( ssh root@$HOST "env PGUSER=user PGPASSWORD=pw $PGDUMP -Fc $ALLDUMPS" | 
          pbzip2 2>&1 > "$BASEDIR/$FILEDATE-$HOST-$ALLDUMPS.dump.bz2" )
if [ $? -ne 0 ]; then
   subj="dbdumper could not create a backup of $ALLDUMP from $HOST"
   mutt -s "$subj" me@myemail.com <<< "$stderr"
fi


来源:https://stackoverflow.com/questions/6784295/capturing-and-mailing-bash-script-errors

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