一个好用的mysql备份脚本

发布时间:2020-10-24编辑:脚本学堂
本文介绍下,一个好用的mysql备份脚本,加到定时任务中,实现定时备份mysql数据库。有需要的朋友参考下。

一个备份mysql脚本

备份目录:/data/data_store/
脚本目录:/data/data_store/

#vim mysql_backup
 

复制代码 代码示例:

#!/bin/bash
#edit by www.jb200.com
DBUser=backup
DBPasswd="123456"
DBHost=192.168.8.112
DBName=`echo "select SCHEMA_NAME from information_schema.SCHEMATA where schema_name not in ('information_schema','test');" | mysql -h$DBHost -u$DBUser -p$DBPasswd --skip-column-names --silent`
BackupPath=/data/data_store
LogFile=/data/data_store/log/mysql_backup.log
NewFile=$(date +%Y%m%d).tgz
OldFile=$(date +%Y%m%d --date='7 days ago').tgz

pushd $BackupPath >> $LogFile
echo $OldFile
echo "----------" >> $LogFile
echo $(date +"%Y-%m-%d %H:%M:%S") >> $LogFile
echo "----------" >> $LogFile
#Delete Old File
if [ -f $OldFile ]
then
     rm -f $OldFile >> $LogFile 2>&1
     echo "[$OldFile]Delete Old File Success!" >> $LogFile
else
     echo "[$OldFile]No Old Backup File!" >> $LogFile
fi

#backup mysql
if [ -f $NewFile ]
then
   echo "[$NewFile]The Backup File is exists,Can't Backup!" >> $LogFile
else
   for item in $DBName
   do
      DumpFile=$item".sql"
      mysqldump -h$DBHost -u$DBUser -p$DBPasswd -R --triggers --single-transaction --flush-logs --master-data --database $item > $DumpFile
   done
   /bin/tar czvf $NewFile *.sql >> $LogFile 2>&1
   /bin/rm -f *.sql
fi
echo "--------" >> $LogFile
popd >> $LogFile

设置计划任务,每天凌晨备份:
 

复制代码 代码示例:
#crontab -e
0 1 * * * /bin/bash /data/data_store/mysql_backup