shell+cron实现MySQL自动备份且自动删除N天前备份

安装crond

yum install vixie-cron crontabs

先上脚本

[shell]
#!/bin/sh
DUMP=/usr/local/mysql/bin/mysqldump
OUT_DIR=/home/liheyuan/xxx/backup/
LINUX_USER=liheyuan

DB_NAME=liheyuan
DB_USER=liheyuan
DB_PASS=xxx
#How much days backup most
DAYS=1

#Core of script
cd $OUT_DIR
DATE=`date +%Y_%m_%d`
OUT_SQL="$DATE.sql"
TAR_SQL="mysql_$DATE.tar.gz"
$DUMP --default-character-set=utf8 --opt -u$DB_USER -p$DB_PASS $DB_NAME > $OUT_SQL
tar -czf $TAR_SQL ./$OUT_SQL
rm $OUT_SQL
chown $DB_NAME:nobody ./$TAR_SQL
find ./ -name "mysql*" -type f -mtime +$DAYS -exec rm {} \;
[/shell]

mysqldump不用解释了吧,注意-uuser -ppass这样才可以,不能有空格。

find ./ -name "mysql*" -type f -mtime +$DAYS -exec rm {} \;

这一句主要是在-mtime上-mtime +5表示5天前的文件,统一删除

我的操作系统是CentOS 5.4,只要把脚本拷贝到/etc/cron.daily,并设置为相同的权限就可以执行了,不用再添加crontab。

Leave a Reply

Your email address will not be published. Required fields are marked *