mysql 自动备份

环境

centos 6.5
mysql 5.7.14

实现功能

备份所有数据库,并且保留最近五天的数据。


#!/bin/sh  
# mysql_backup.sh: backup mysql databases and keep newest 5 days backup.  
#  
# db_user is mysql username  
# db_passwd is mysql password  
# db_host is mysql host  
# —————————–  
db_user="root"  
db_passwd="12345678"  
db_host="localhost"  

# the directory for story your backup file.  
backup_dir="/home/mysqlbackup"  

# date format for backup file (dd-mm-yyyy)  
time="$(date +"%d-%m-%Y")"  

# mysql, mysqldump and some other bin's path  
MYSQL="/usr/bin/mysql"  
MYSQLDUMP="/usr/bin/mysqldump"  
MKDIR="/bin/mkdir"  
RM="/bin/rm"  
MV="/bin/mv"  
GZIP="/bin/gzip"  

# check the directory for store backup is writeable  
test ! -w $backup_dir && echo "Error: $backup_dir is un-writeable." && exit 0  

# the directory for story the newest backup  
test ! -d "$backup_dir/backup.0/" && $MKDIR "$backup_dir/backup.0/"  

# get all databases  
all_db="$($MYSQL -u $db_user -h $db_host -p$db_passwd -Bse 'show databases')"  
for db in $all_db  
do  
$MYSQLDUMP -u $db_user -h $db_host -p$db_passwd $db --skip-lock-tables | $GZIP -9 > "$backup_dir/backup.0/$time.$db.gz"  
done  

# delete the oldest backup  
test -d "$backup_dir/backup.5/" && $RM -rf "$backup_dir/backup.5"  

# rotate backup directory  
for int in 4 3 2 1 0  
do  
if(test -d "$backup_dir"/backup."$int")  
then  
next_int=`expr $int + 1`  
$MV "$backup_dir"/backup."$int" "$backup_dir"/backup."$next_int"  
fi  
done  
exit 0;

需要注意的是,备份目录在备份动作执行前,需要手动创建,然后通过root账号,使用crontab执行定时任务。

可能出现的问题

The 'INFORMATION_SCHEMA.GLOBAL_STATUS' feature is disabled: see the documentation for 'show_compatibility_56'
解决方法:进入mysql命令模式,执行以下sql语句

set @@global.show_compatibility_56=ON;
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 在数据库的日常维护工作中,除了保证业务的正常运行以外,就是要对数据库进行备份,以免造成数据库的丢失,从而给企业带来...
    风澈vio阅读 14,118评论 11 30
  • 概述 把mysql数据库默认数据目录下面的database-name数据库备份到/data/mysql_bak里面...
    syncwt阅读 9,460评论 0 4
  • @REM 版本 1.4 @REM 要测试是否能成功运行,请在配置好以下参数后,直接运行,看能否正常备份MySQL数...
    getforever阅读 8,346评论 0 3
  • 备份需求 数据库备份的重要性再怎么强调也不为过。当你的操作出现差错,但又因为没有作备份导致数据无法还原时,你就能体...
    闲睡猫阅读 4,459评论 1 5
  • 社交网络每天都有很多人在分享信息,但不是每个人都如此,有的人却一言不发。 所以我们看到的可能是某些有偏见的不对...
    meychang阅读 2,844评论 0 0

友情链接更多精彩内容