1 #function:MYSQL自动全备 2 #version:1.0.0 3 #author:wangyanlin 4 #date:2017/08/03 5 #----------------------------------------------------------------------------------------------- 6 #!/bin/sh 7 #创建目录 8 MAIN=`cd / && mkdir -p mysql_bak` 9 MAIN1=`mkdir -p /mysql_bak/all_data` 10 LOGS=`mkdir -p /mysql_bak/logs` 11 #指定参数 12 DATE=`date +%Y%m%d%H%M%S` 13 DATE1=`date +%Y%m%d` 14 DB_user=root 15 DB_password=123456 16 #MySQL全备使用mysqldump命令 17 start_time=`date +'%Y-%m-%d %H:%M:%S'` 18 echo "$DATE数据库全备开始......" >> /mysql_bak/logs/Full_Bak_$DATE1.log 19 /usr/bin/mysqldump --all-databases --default-character-set=utf8 --flush-logs -u$DB_user -p$DB_password > /mysql_bak/all_data/Full_Bak_$DATE.sql 20 if [ $? -eq 0 ] 21 then 22 echo "$DATE数据库备份成功......" >> /mysql_bak/logs/Full_Bak_$DATE1.log 23 cd /mysql_bak/all_data/ 24 /usr/bin/tar -zcvf Full_Bak_$DATE.sql.tar.gz Full_Bak_$DATE.sql > /dev/null 25 if [ $? -eq 0 ] 26 then 27 echo "$DATE数据库备份打包成功......" >> /mysql_bak/logs/Full_Bak_$DATE1.log 28 /usr/bin/find /mysql_bak/all_data/ -name "Full_Bak_*.*" -mtime +7 -exec rm -rf {} ; /usr/bin/find /mysql_bak/logs/ -name "Full_Bak_*.log" -mtime +7 -exec rm -rf {} ; 29 else 30 echo "$DATE数据库备份打包失败......" >> /mysql_bak/logs/Full_Bak_$DATE1.log 31 exit 0 32 fi 33 else 34 echo "$DATE数据库备份失败......" >> /mysql_bak/logs/Full_Bak_$DATE1.log 35 cd /mysql_bak/all_data/ 36 rm -rf Full_Bak_$DATE.sql 37 exit 0 38 39 fi 40 end_time=`date +'%Y-%m-%d %H:%M:%S'` 41 start_seconds=$(date --date="$start_time" +%s); 42 end_seconds=$(date --date="$end_time" +%s); 43 echo "本次备份运行时间: "$((end_seconds-start_seconds))"s" >> /mysql_bak/logs/Full_Bak_$DATE1.log
添加计划任务:
crontab -e
00 00 * * 6 /root/MySQL_allbak.sh #每周六的凌晨00点开始全备
logs日志打印出来的效果:
使用前请将备份的路径自行更改,后期会更新MySQL数据库自动增量备份的脚本代码和手动交互式备份数据库的代码,有问题请指出,新手刚写,大神勿喷!