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文件夹中七天前的文件是否存在,存在则删除,最后结束。这样就能自动备份最近七天的数据库脚本。
这是博主的服务器截图:
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