我自己编写了一个shell脚本来备份我们的Web服务器并使其正常工作。它导航到备份目录,一个rsync,一个mysqldump,将它全部提交给git存储库进行版本控制并将其推送到我们的远程git服务器。我已经知道编写预定的UNIX脚本有很多陷阱,所以我想知道我是否遗漏了任何东西或者让自己陷入了灾难。如何在整个过程中向我发送任何错误的电子邮件?
#!/bin/bash
#Exit on any error
set -e
LOGFILE=~/backups/web_backup-$(date +"%m.%d.%Y_%H.%M.%S").log
touch $LOGFILE
echo "Backup started for "$(date +"%m.%d.%Y_%H.%M.%S") | tee -a $LOGFILE
############################################################
###### BACKUP WEBSITE
############################################################
echo "Backing up Website..." 2>&1 | tee -a $LOGFILE
cd ~/backups/example.org
if [ "$?" != "0" ]; then
echo "Cannot change directory!" 1>&2
exit 1
fi
rsync -Pav --size-only --delete --filter='P .git' --filter='P example.com.sql' backups@example.com:/path/to/example.org/ ~/backups/example.org/ 2>&1 | tee -a $LOGFILE
echo "Backing up Example.com DB..." 2>&1 | tee -a $LOGFILE
ssh backups@example.com "mysqldump -u user -hlocalhost -ppassword dbname > example.com.sql
echo "Adding files to Git Repository..." 2>&1 | tee -a $LOGFILE
git add . 2>&1 | tee -a $LOGFILE| tee -a $LOGFILE
echo "Commiting files to Git Repository..." 2>&1 | tee -a $LOGFILE
git commit -m "Backup as of "$(date +"%m.%d.%Y_%H.%M.%S") 2>&1 | tee -a $LOGFILE
echo "Pusing Git Repo to Remote Location..." 2>&1 | tee -a $LOGFILE
git push origin master 2>&1 | tee -a $LOGFILE
echo "Finished backing up Website..." 2>&1 | tee -a $LOGFILE
echo "Backup Finished for "$(date +"%m.%d.%Y_%H.%M.%S")
exit
答案 0 :(得分:0)
在脚本中声明一个报告文件,并将所有输出定向到该文件。检查复制和rsynch命令的退出状态($?),如果退出状态不等于零,则使用邮件命令邮件到报告文件的地址
mail -s "subject " -c "cc address" "to-address" < reportfile name