Centos 自动备份mysql

分类:CentOS教程 阅读:45780 次

1、创建备份文件夹

  1. cd/mnt/cp_disk/
  2. mkdirbackup
  3. cdbackup
  4. mkdirdatabak
  5. mkdirdb
  6. mkdirlogs

2、编写执行脚本

  1. #!/bin/bash
  2. backup_dir=/mnt/cp_disk/backup/databak#备份临时文件存放目录
  3. backup_target_dir=/mnt/cp_disk/backup/db#备份文件存放目录
  4. backup_logs_dir=/mnt/cp_disk/backup/logs#备份日志目录
  5. db=gzcpc
  6. DATE=$(date+%Y%m%d)
  7. #得到10天前的日期
  8. ccDATE=$(date"-d10dayago"+%Y%m%d)
  9. echo"开始复制数据表">>$backup_logs_dir/$db$DATE
  10. echo"-----------`date+"%Y-%m-%d%H:%M:%S"`--------------------">>$backup_logs_dir/$db$DATE
  11. cp-R/var/lib/mysql/$db$backup_dir/#mysql数据库的数据目录为/var/lib/mysql/
  12. echo"开始压缩数据表">>$backup_logs_dir/$db$DATE
  13. echo"------------------------">>$backup_logs_dir/$db$DATE
  14. cd$backup_dir
  15. tar-zcvf$db$DATE.tar.gz$db/&&echo"压缩表结束">>$backup_logs_dir/$db$DATE
  16. mv$db$DATE.tar.gz$backup_target_dir/&&echo"转移成功">>$backup_logs_dir/$db$DATE
  17. if[$?-eq0]
  18. then
  19. echo"backupsucceed">>$backup_logs_dir/$db$DATE
  20. else
  21. echo"backupfail">>$backup_logs_dir/$db$DATE
  22. fi
  23. echo"开始删除原数据表">>$backup_logs_dir/$db$DATE
  24. echo"-----------------------">>$backup_logs_dir/$db$DATE
  25. rm-rf$backup_dir/*&&echo"删除原数据表">>$backup_logs_dir/$db$DATE
  26. echo"删除10天前数据">>$backup_logs_dir/$db$DATE
  27. if[-e$backup_target_dir/db$ccDATE.tar.gz]
  28. then
  29. rm-rf$backup_target_dir/db$ccDATE.tar.gz
  30. echo"Delete$backup_target_dir/db$ccDATE.tar.gzsucceed">>$backup_logs_dir/$db$DATE
  31. else
  32. echo"Notfound$backup_target_dir/db$ccDATE.tar.gzfile">>$backup_logs_dir/$db$DATE
  33. fi
  34. if[-e$backup_logs_dir/$db$ccDATE]
  35. then
  36. rm-rf$backup_logs_dir/$db$ccDATE
  37. echo"Delete$backup_logs_dir/$db$ccDATEsucceed">>$backup_logs_dir/$db$DATE
  38. else
  39. echo"Notfound$backup_logs_dir/$db$ccDATEfile">>$backup_logs_dir/$db$DATE
  40. fi

3、赋予脚本权限

  1. chmod755/home/backup_mysql.sh

4、创建定时任务

  1. crontab–e
  2. 10***/bin/bash/home/backup_mysql.sh