1.先在服务器下建文件夹以下3个文件夹:
mkdir /backup,mkdir /backup/bakmysql,mkdir /backup/bakmysqlold
在/backup文件夹下建一个shell脚本
touch dev/shm/bak/backup/backup.sh
给文件授权:
chmod 755 /dev/shm/backup/backup.sh2.编辑shell脚本
vi /dev/shm/backup/backup.sh #!/bin/bash cd /dev/shm/backup/bakmysql echo "You are in backup directory" mv yhb* /dev/shm/backup/bakmysqlold echo "Old databases are moved to bakmysqlold folder" Now=$(date +"%d-%m-%Y_%H%M%S") File=yhb-$Now.sql /usr/local/mysql/bin/mysqldump -uyhb -p'yhb' yhb > $File echo "Your database backup successfully completed" SevenDays=$(date -d -7day +"%d-%m-%Y_%H%M%S") if [ -f /dev/shm/backup/bakmysqlold/yhb-$SevenDays.sql ] then rm -rf /dev/shm/backup/bakmysqlold/yhb-$SevenDays.sql echo "You have delete 7days ago bak file " else echo "7days ago bak file not exist " fi3.shell脚本说明:mysqldump -uroot -p'password' yhb> $File 这句中的红色字体请分别换为你自己的mysql数据库用户、密码和database名。脚本先将/dev/shm/backup/bakmysql文件夹下bakmysql为文件名开头的备份文件移至/dev/shm/backup/bakmysqlold,再生成最新的备份文件,最后再判断/dev/shm/backup/bakmysqlold文件夹中七天前的文件是否存在,存在则删除,最后结束。这样就能自动备份最近七天的数据库脚本。
4.设置每天自动执行shell脚本
crontab -e在最后加入这样一行,编辑
*/1 * * * * /dev/shm/backup/backup.sh测试任务是否执行
tail -f /var/log/cron