1、MySQL自动备份脚本
# vi /opt/scritps/db_backup.sh #!/bin/bash USER=root PASSWORD=123456 DATABASE1=test-db1 #DATABASE2=test-db2 BACKUP_DIR="/opt/data_bankup/" LOGFILE=/opt/data_bankup/data_backup.log DATE=`date +%Y%m%d-%H%M` DUMPFILE1=appnest-$DATE.sql DUMPFILE2=imserver-$DATE.sql ARCHIVE1=$DUMPFILE1-tar.gz ARCHIVE2=$DUMPFILE2-tar.gz # ### Backup test-db1 Database ### if [ ! -d $BACKUP_DIR ];then mkdir -p "$BACKUP_DIR" fi echo -e " " >> $LOGFILE echo "------------------------------------" >> $LOGFILE echo " BACKUP DATE:$DATE" >> $LOGFILE echo "------------------------------------" >> $LOGFILE cd $BACKUP_DIR /opt/thirdsoft-installed/mysql/mysql/bin/mysqldump -u$USER -p$PASSWORD $DATABASE1 > $DUMPFILE1 if [[ $? == 0 ]];then tar -zcf $ARCHIVE1 $DUMPFILE1 >> $LOGFILE 2>&1 echo "$DATABASE1 DATABASE BACKUP SUCCESSFUL!" >> $LOGFILE rm -f $DUMPFILE1 else echo “$DATABASE1 Backup Fail!” >> $LOGFILE fi # ### Backup test-db2 Database ### /opt/thirdsoft-installed/mysql/mysql/bin/mysqldump -u$USER -p$PASSWORD $DATABASE2 > $DUMPFILE2 if [[ $? == 0 ]];then tar -czf $ARCHIVE2 $DUMPFILE2 >> $LOGFILE 2>&1 echo "$DATABASE2 DATABASE BACKUP SUCCESSFUL!" >> $LOGFILE rm -f $DUMPFILE2 else echo "$ARCHIVE2 Backup Fail!" >> $LOGFILE fi
2、批量删除N天前的旧备份
# vi /opt/scritps/del_oldDB_backup.sh #!/bin/bash BACKUPDIR="/opt/data_bankup/" KEEPTIME=15 //需要删除的文件距离当前的天数 DELFILE=`find $BACKUPDIR -type f -mtime +$KEEPTIME -exec ls {} ;` for delfile in ${DELFILE} rm -f $delfile done
3、设定计划任务
# crontab -e 0 2 * * * root /opt/scritps/db_backup.sh /dev/null 2>&1 #定义每天凌晨2点执行备份数据库脚本 0 3 * * 0 root /opt/scritps/del_oldDB_backup.sh /dev/null 2>&1 #定义每周日凌晨3点执行删除数据库备份文件
crontab 时间表示
项目 | 含义 | 范围 |
---|---|---|
第一个"*" | 一小时当中的第几分钟(minute) | 0~59 |
第二个"*" | 一天当中的第几小时(hour) | 0~23 |
第三个"*" | 一个月当中的第几天(day) | 1~31 |
第四个"*" | 一年当中的第几个月(month) | 1~12 |
第五个"*" | 一周当中的星期几(week) | 0~7(0和7都代表星期日) |