mysqldump.sh 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #!/bin/bash
  2. # sh mysqldump.sh > output.log 2>&1
  3. # mysql数据库备份脚本, 备份保留7天
  4. # MYSQL_USER: Mysql用户名
  5. # MYSQL_PASSWORD: Mysql用户密码
  6. # BACKUP_ROOT: 备份目录文件: 备份目录
  7. # BACKUP_DB: 备份数据库名称: 备份数据库
  8. # REMOTE_USER: 冗余备份远程机器用户名
  9. # REMOTE_HOST: 冗余备份远程机器主机
  10. MYSQL_USER=
  11. MYSQL_PASSWORD=
  12. BACKUP_ROOT=
  13. BACKUP_DB=
  14. REMOTE_USER=
  15. REMOTE_HOST=
  16. BACKUP_DATE=`date +%Y-%m-%d`
  17. BACKUP_EXIPRE_DATE=`date +%Y-%m-%d -d -7day`
  18. # 备份sql
  19. BACKUP_SQL=${BACKUP_DB}_${BACKUP_DATE}.sql
  20. # 打包压缩备份
  21. BACKUP_SQL_TARGZ=${BACKUP_DATE}.tar.gz
  22. # 已过期的备份
  23. BACKUP_SQL_EXPIRE_TARGZ=${BACKUP_EXIPRE_DATE}.tar.gz
  24. # 备份日志文件
  25. BACKUP_LOG=mysqldump.log
  26. cd ${BACKUP_ROOT}
  27. # 1.全量备份mysql数据库
  28. echo "`date +'%Y-%m-%d %H:%M:%S'` mysqldump ${BACKUP_DB} start." >> ${BACKUP_LOG}
  29. mysqldump -u${MYSQL_USER} -p${MYSQL_PASSWORD} --single-transaction --flush-logs --master-data ${BACKUP_DB} > ${BACKUP_SQL}
  30. if [ $? -ne 0 ];then
  31. echo "`date +'%Y-%m-%d %H:%M:%S'` mysqldump ${BACKUP_DB} error." >> ${BACKUP_LOG}
  32. return
  33. fi
  34. # 2.数据库文件打包压缩, 删除备份过期文件
  35. tar -zcvf ${BACKUP_SQL_TARGZ} ${BACKUP_SQL}
  36. rm -f ${BACKUP_SQL}
  37. rm -f ${BACKUP_SQL_EXPIRE_TARGZ}
  38. # 3.拷贝到远端服务器,冗余备份
  39. echo "`date +'%Y-%m-%d %H:%M:%S'` mysqldump ${BACKUP_DB} scp remote." >> ${BACKUP_LOG}
  40. scp ${BACKUP_SQL_TARGZ} ${REMOTE_USER}@${REMOTE_HOST}:${BACKUP_ROOT}
  41. ssh ${REMOTE_USER}@${REMOTE_HOST} rm -f ${BACKUP_ROOT}${BACKUP_SQL_EXPIRE_TARGZ}
  42. echo "`date +'%Y-%m-%d %H:%M:%S'` mysqldump ${BACKUP_DB} finish." >> ${BACKUP_LOG}