【问题标题】:Error Handling For A Mac/UNIX Shell Script to Backup Our Web Servers and MySQL Databases用于备份 Web 服务器和 MySQL 数据库的 Mac/UNIX Shell 脚本的错误处理
【发布时间】:2012-07-24 05:51:04
【问题描述】:

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

【问题讨论】:

    标签: git bash shell unix


    【解决方案1】:

    在脚本中声明一个报告文件并将所有输出指向它。检查复制和 rsynch 命令的退出状态($?)如果退出状态不等于零,则使用 mail 命令将邮件发送到包含报告文件的地址

    mail -s "subject " -c "cc address" "to-address" < reportfile name
    

    【讨论】:

      猜你喜欢
      • 2013-11-09
      • 1970-01-01
      • 1970-01-01
      • 2010-10-31
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多