Linux下MySQL自动备份

备份账号

dump.cnf

1
2
3
[mysqldump]
user = maxzhao
password = xxx

简单脚本

1
2
3
4
5
6
7
8
9
#!/bin/bash
echo 'start 备份'
current="`date +%Y%m%d%H%M%S`"
mysqldump --defaults-file=/opt/mysql8/dump.cnf -h 192.168.3.55 -A > /opt/mysql8/dump/55-${current}.sql
echo '已备份为SQL文件:55-${current}.sql'
cd /opt/mysql8/dump/
tar -zcf 55-${current}.tar.gz 55-${current}.sql
rm -f 55-${current}.sql
echo '备份成功:55-${current}.tar.gz'

定时备份

1
crontab -e

输入

1
0 0,12 * * * /opt/mysql8/55-dump.sh

执行

1
systemctl restart crond

没有当前命令则需要安装

1
sudo yum -y install crontabs

删除 30天前的备份

编辑 vim

1
2
3
4

echo '#!/bin/bash' > /opt/mysql8/dump_limit.sh
echo 'find /opt/mysql8/dump/ -type f ! -newermt "30 days ago" -delete' >> /opt/mysql8/dump_limit.sh
chmod u+x /opt/mysql8/dump_limit.sh

同样的

1
crontab -e

输入

1
2
0 0,12 * * * /opt/mysql8/55-dump.sh
0 0,12 * * * /opt/mysql8/dump_limit.sh

本文地址: https://github.com/maxzhao-it/blog/post/3ed70945/