捕获和邮寄的bash脚本错误 [英] Capturing and mailing bash script errors
本文介绍了捕获和邮寄的bash脚本错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有我的cron在夜间运行备份一些Postgres数据库用我的网络上的多个主机的脚本。我有越来越警觉,该脚本通过利用退出状态失败的一种方式,但它并没有告诉我为什么失败了。
根据折以下code,我怎么能捕捉到当脚本运行时出现的任何错误,并通过电子邮件发送给我,让我能有一个更好的了解所发生的事情。
FILEDATE ='日期'+%Y-%M-%D'`
BASEDIR = / U1 / $ 1 / db_dumps
PGDUMP = /路径/要/ pg_dump的
HOST = $ 1
DB = $ 16如果[$ DB ==全部]
然后
为DB1 DB2 DB3 ALLDUMPS
做
SSH根@ $ HOSTENV PGUSER = PGUSER PGPASSWORD = $ PGPASSWORD -Fc PGDUMP $ ALLDUMPS| pbzip2> $ BASEDIR / $ FILEDATE- $ HOST- $ ALLDUMPS.dump.bz2
如果[$? -ne 0]
然后狗-sdbdumper无法创建$ ALLDUMP从$ HOST备份me@myemail.com<的/ dev / null的
科幻
DONE其他
SSH根@ $ HOSTENV PGUSER = PGUSER PGPASSWORD = $ PGPASSWORD -Fc PGDUMP $ DB| pbzip2> $ BASEDIR / $ FILEDATE- $ HOST- $ DB.dump.bz2
如果[$? -ne 0]
然后狗-sdbdumper无法创建$ DB从$ HOST备份me@myemail.com<的/ dev / null的
科幻
科幻
解决方案
从SSH命令捕获标准错误,并通过电子邮件发送,为你自己。
标准错误= $(SSH根@ $ HOSTENV PGUSER =用户PGPASSWORD = PW $ PGDUMP -Fc $ ALLDUMPS|
pbzip2 2 - ;&放大器1为卤素; $ BASEDIR / $ FILEDATE- $ HOST- $ ALLDUMPS.dump.bz2)
如果[$? -ne 0];然后
SUBJ =dbdumper无法创建$ ALLDUMP从$ HOST备份
狗-s$ SUBJme@myemail.com<<< $标准错误
科幻
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
解决方案
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
这篇关于捕获和邮寄的bash脚本错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文