CentOS Linux下每天自动备份MySQL数据库

CentOS Linux下每天自动备份MySQL数据库

1.先在服务器下建文件夹以下3个文件夹:mkdir /bak,mkdir /bak/bakmysql,mkdir /bak/bakmysqlold 。在/bak/bakmysql文件夹下建一个shell脚本:touch /bak/bakmysql/backup.sh 。

给文件授权:chmod 755 /bak/bakmysql/backup.sh 。

2.编辑shell脚本:vi /bak/bakmysql/backup.sh
#!/bin/sh
cd /bak/bakmysql
echo "You are in bakmysql directory"
mv bakmysql* /bak/bakmysqlold
echo "Old databases are moved to bakmysqlold folder"
Now=$(date +"%d-%m-%Y")
File=bakmysql-$Now.sql
mysqldump -uroot -p'password' db_bbs > $File
echo "Your database backup successfully completed"
SevenDays=$(date -d -7day  +"%d-%m-%Y")
if [ -f /bak/bakmysqlold/bakmysql-$SevenDays.sql ]
then
rm -rf /bak/bakmysqlold/bakmysql-$SevenDays.sql
echo "You have delete 7days ago bak file "
else
echo "7days ago bak file not exist "
fi

3.shell脚本:mysqldump -uroot -p'password' db_bbs> $File 这句中的红色字体请分别换为你自己的mysql数据库用户、密码和database名。脚本先将/bak/bakmysql文件夹下bakmysql为文件名开头的备份文件移至/bak/bakmysqlold,再生成最新的备份文件,最后再判断/bak/bakmysqlold文件夹中七天前的文件是否存在,存在则删除,最后结束。这样就能自动备份最近七天的数据库脚本。

这是博主的服务器截图:

CentOS Linux下每天自动备份MySQL数据库

4.设置每天自动执行shell脚本:vi /etc/crontab 在最后加入这样一行(具体含义请自行参考/etc/crontab中的注释):0 0 * * * root /bak/bakmysql/backup.sh 。重启crontab:/sbin/service crond restart 。如果没有设置crontab为开机自启动可以如下设置其开机自启动:chkconfig –level 35 crond on

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/8e58104343c53bdeebabc21ebac7bd09.html