捕获并邮寄 bash 脚本错误
我有一个脚本,每晚在 cron 中运行,为网络上的多个主机备份一些 postgres 数据库。我有一种方法可以通过利用退出状态来收到脚本失败的警报,但它没有告诉我失败的原因。
根据以下代码,我如何捕获脚本运行时发生的任何错误,并将其通过电子邮件发送给我,以便我可以更好地了解发生的情况。
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" [email protected] < /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" [email protected] < /dev/null
fi
fi
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" [email protected] < /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" [email protected] < /dev/null
fi
fi
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从 ssh 命令捕获 stderr,并将其通过电子邮件发送给自己。
Capture stderr from the ssh command, and email that to yourself.