我为自己编写了一个 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