2012-07-25 15 views
0

我寫了一個shell腳本來備份我們的Web服務器並使其工作。它導航到備份目錄,一個rsync,一個mysqldump,將它全部提交給git倉庫進行版本控制,並將其推送到我們的遠程git服務器。我已經瞭解到,編寫預定的UNIX腳本有很多缺陷,所以我想知道我是否錯過了任何東西或是爲自己設置了自己的災難。如何在整個過程中給我發電子郵件?錯誤處理Mac/UNIX Shell腳本來備份我們的Web服務器和MySQL數據庫

#!/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' [email protected]:/path/to/example.org/ ~/backups/example.org/ 2>&1 | tee -a $LOGFILE 

echo "Backing up Example.com DB..." 2>&1 | tee -a $LOGFILE 

ssh [email protected] "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

在腳本中聲明報告文件並將所有輸出指向它。檢查退出狀態什麼都使用,如果退出狀態不等於零,然後使用mail命令郵件地址與報告文件

mail -s "subject " -c "cc address" "to-address" < reportfile name 
複製和rsynch命令($?)