#!/bin/bash
#backup_MySQL_data
#检查目录权限
BackupDir=/data/dumpbackup
SaveDir=/data/dumpbackup/data
fdate=`date "+%Y%m%d%H%M%S"`
chown -R mysql:mysql $BackupDir
chmod -R 775 $BackupDir
chmod -R 775 $SaveDir
#备份database库
function database () {
echo "`date "+%m %d %H:%M:%S"` Begin backup database" >> $BackupDir/backmysql.log
if [ ! -d $BackupDir/mysql ];then
mkdir -p $BackupDir/mysql
fi
chown -R mysql:mysql $BackupDir/mysql
/opt/mysql/mysql-8.0.25-linux-glibc2.12-x86_64/bin/mysqldump -h192.168.65.228 -P 3306 -u admin -p'password' databaseName --set-gtid-purged=off > $BackupDir/mysql/database_$fdate.sql
echo "`date "+%m %d %H:%M:%S"` backup database done" >> $BackupDir/backmysql.log
}
#压缩删除备份文件
function compress () {
echo "`date "+%m %d %H:%M:%S"` Begin complete database " >> $BackupDir/backmysql.log
chown -R mysql:mysql $BackupDir/
cd $BackupDir
tar zcvPf $BackupDir/mysql_$fdate.tar.gz $BackupDir/mysql/database_$fdate.sql
if [ ! -d $SaveDir ];then
mkdir -p $SaveDir
fi
cd $BackupDir
cp $BackupDir/mysql_$fdate.tar.gz $SaveDir
rm -fr $BackupDir/mysql/database_$fdate.sql
rm -fr $BackupDir/mysql_$fdate.tar.gz
echo "`date "+%m %d %H:%M:%S"` copy data to savedir done" >> $BackupDir/backmysql.log
#判断备份文件数是否大于3
nuf=`find $SaveDir -name '*.tar.gz' -size +10M|wc -l`
if [[ $? -eq 0 && $nuf -gt 3 ]];then
#删除3天之前的数据
find $SaveDir -name '*.tar.gz' -mtime +3 -exec rm -rf {} ;
echo "`date "+%m %d %H:%M:%S"` delete nfs than 3 days" >> $BackupDir/backmysql.log
fi
echo `date "+%m %d %H:%M:%S"` "All is OK" >> $BackupDir/backmysql.log
cp -r $BackupDir/backmysql.log $SaveDir
}
database
compress
echo $fdate "mysql数据库备份完成"