Shell

mysqldump成功後發送郵件

  • January 14, 2020

我有一個腳本,它將通過 mysqldump 備份 mysql db。如果轉儲成功或失敗,我想在此腳本中添加另一個選項以發送自動電子郵件。

這是腳本:

#!/bin/sh
BACKUP=/data/backup/sql2/new_backup/daily
cd $BACKUP
mkdir `date '+%d-%m-%Y'`
NOW=$(date +"%d-%m-%Y")

MUSER="root"
MPASS="mypass"
MHOST="sql4"
MYSQL="$(which mysql)"
MYSQLDUMP="$(which mysqldump)"
GZIP="$(which gzip)"

DBS="$($MYSQL -u $MUSER -h $MHOST -p$MPASS -Bse 'show databases')"
for db in $DBS
do
FILE=$BACKUP/$NOW/mysql-$db.$NOW-$(date +"%T").sql.gz
$MYSQLDUMP -u $MUSER -h $MHOST -p$MPASS --lock-all-tables $db | $GZIP -9 > $FILE
done

我怎樣才能做到這一點?

mysqldump``0如果一切順利,將以退出程式碼結束。你可以使用它:

#!/bin/sh
BACKUP=/data/backup/sql2/new_backup/daily
cd $BACKUP
mkdir `date '+%d-%m-%Y'`
NOW=$(date +"%d-%m-%Y")

MUSER="root"
MPASS="mypass"
MHOST="sql4"
MYSQL="$(which mysql)"
MYSQLDUMP="$(which mysqldump)"
GZIP="$(which gzip)"
MAIL="youradress@example.com"
MAILER="$(which mail)"
STATUSFILE="/tmp/statusfile.$NOW"


echo "Backup report from $NOW" > $STATUSFILE
DBS="$($MYSQL -u $MUSER -h $MHOST -p$MPASS -Bse 'show databases')"
for db in $DBS
do
FILE=$BACKUP/$NOW/mysql-$db.$NOW-$(date +"%T").sql.gz
$MYSQLDUMP -u $MUSER -h $MHOST -p$MPASS --lock-all-tables $db | $GZIP -9 > $FILE
if [ "$?" -eq "0" ] then; 
  echo "$db backup is OK" >> $STATUSFILE
 else 
  echo "##### WARNING: #####  $db backup failed" >> $STATUSFILE
 fi
done
$MAILER -s "Backup report for $NOW" -- $MAIL < $STATUSFILE
rm $STATUSFILE

我沒有對此進行測試,但這是執行此操作的一般方法。

引用自:https://serverfault.com/questions/262473