Linux下使用crontab自动备份数据库
这里使用到crontab定时任务的添加及mysqldump执行简单的数据库备份,具体步骤如下:
1. 编写一个脚本: /serverBack/autobackmysql.sh
内容如下:
方法一:
##使用mysqldump备份数据库erms
/usr/local/mysql/bin/mysqldump -uroot -ppwd erms >> /serverBack/mysql_back/erms_$(date+"%Y_%m_%d").sql
##找到/serverBack/mysql_back/下文件名称以erms_开头,以 .sql 结尾的文件,并且是7天前系统修改过的文件,将其删除
find /serverBack/mysql_back/ -mtime +7-name "erms_*.sql" -exec rm -rf {} \;
方法二:
/usr/local/mysql/bin/mysqldump -uroot -ppwd dbname > dir/db_`date +%F`.sql
##保留近一周的备份文件,更早的删除
find /dir -mtime +7 -name"db_*.sql" -exec rm -rf {} \;
方法三:
filename='date +%y%m%d'
/usr/local/mysql/bin/mysqldump -uroot-proot erms >>/serverBack/mysql/$filename.sql
较全的shell脚本内容如下:
echo "---------------------------------------------------" >> /serverBack/dbBack/dbBackLog.log echo $(date +"%Y-%m-%d %H:%M:%S") "erms Database backup start" >> /serverBack/dbBack/dbBackLog.log /usr/local/mysql/bin/mysqldump -uroot -ppwd erms >> /serverBack/dbBack/erms_$(date +"%Y-%m-%d").sql if [ 0 -eq $? ];then if [ -f "/serverBack/dbBack/erms_$(date +"%Y-%m-%d").sql" ];then echo $(date +"%Y-%m-%d %H:%M:%S") "erms Database backup success!" >> /serverBack/dbBack/dbBackLog.log else echo $(date +"%Y-%m-%d %H:%M:%S") "erms Database backup fail!" >> /serverBack/dbBack/dbBackLog.log fi else echo $(date +"%Y-%m-%d %H:%M:%S") "erms Database backup error!" >> /serverBack/dbBack/dbBackLog.log fi echo "---------------------------------------------------" >> /serverBack/dbBack/dbBackLog.log find /serverBack/mysql_back/ -mtime +7 -name "erms_*.sql" -exec rm -rf {} \;
注意:a.这里的mysqldump最好是使用绝对路径,若直接使用mysqldump有可能备份成空文件
b.为了确保该脚本内容准确无误,可以单独运行每个命令,如执行mysqldump命令:/usr/local/mysql/bin/mysqldump -uroot -ppwd erms >> /serverBack/mysql_back/erms_$(date+"%Y_%m_%d").sql
c.find命令中,结尾处的 ; 分号不能省略
2. 添加一个定时任务
crontab –e ##编辑定时任务
添加定时任务内容:
00 15 * * * /serverBack/autobackmysql.sh ##每天定时15:00:00 执行脚本 /serverBack/autobackmysql.sh
命令:
crontab –e ##编辑定时任务
crontab –r 删除所有定时任务
crontab –l 列出所有定时任务