曾經之前也有寫過類似mysql全量和增量備份腳本,不過過於簡單。昨天晚上給公司線上服務器寫了個針對mysql5.7的,相對來講更為優化的一個實例。
注:這個腳本僅僅適合小型數據庫,不適合中大型數據庫。畢竟是邏輯備份方式,數據庫過大導入會比較慢,建議采用innobackupex方式備份,包括我自己服務器也是采用的innobackupex。
全量備份腳本:
#!/bin/bash
#bak mysql all
# v1.0
#2016.8.4
TIME=`date +%Y%m%d_%H%M%S`
LOGFILE="/home/mysqlbak/mysql_full_bak_time.log"
MYSQL_BAKDIR="/home/mysqlbak/full$TIME"
USER=root
PASSWORD=xxxxxx
[ ! -d $MYSQL_BAKDIR ] && mkdir -p $MYSQL_BAKDIR
[ ! -e $LOGFILE ] && touch $LOGFILE
DATABASE=`mysqlshow -u$USER -p$PASSWORD | grep -Ev "Data|info|per|sys" | grep -v + | awk '{print $2}'`
for bakmysqlname in $DATABASE
do
mysqldump -u$USER -p$PASSWORD $bakmysqlname --skip-lock-tables > $MYSQL_BAKDIR/$TIME_$bakmysqlname.sql
tar zcf $MYSQL_BAKDIR/$TIME_$bakmysqlname.tar.gz $MYSQL_BAKDIR/$TIME_$bakmysqlname.sql --remove-files &> /dev/null
done
ret=$?
FINISHTIME=`date +%Y%m%d_%H%M%S`
[ $ret -eq 0 ] && echo "Mysql fullbakup finished, time: $FINISHTIME">> $LOGFILE || echo "Mysql fullbakup failed,please check time:$FINISHTIME" >> $LOGFILE
增量備份腳本:
#!/bin/bash
#bak incr for mysql
#2016.8.4
TIME=`date +%Y%m%d_%H%M%S`
DATADIR=/data/mysql
LOGFILE="/home/mysqlbak/mysql_incr__bak_time.log"
USER=root
PASSWORD=xxxxxx
MYSQL_BAKDIR=/home/mysqlbak/incr$TIME
[ ! -d $MYSQL_BAKDIR ] && mkdir -p $MYSQL_BAKDIR
[ ! -e $LOGFILE ] && touch $LOGFILE
mysqladmin -u$USER -p$PASSWORD flush-logs
TOTAL=`ls $DATADIR/mysql-bin.* |wc -l`
TOTAL=`expr $TOTAL - 2`
for filetemp in `ls $DATADIR/mysql-bin.*|head -n $TOTAL`
do
incrfilename=`basename $filetemp`
cp $filetemp $MYSQL_BAKDIR/$incrfilename
tar zcf $MYSQL_BAKDIR/$incrfilename.tar.gz $MYSQL_BAKDIR/$incrfilename --remove-files &> /dev/null
done
ret=$?
FINISHTIME=`date +%Y%m%d_%H%M%S`
[ $ret -eq 0 ] && echo " Mysql incr bak finished,time: $FINISHTIME">> $LOGFILE || echo " Mysql incr bak failed,please check.time: $FINISHTIME">> $LOGFILE