曾經之前也有寫過類似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