mysql_backup_run.sh 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #!/bin/bash
  2. # mysql_backup.sh: backup mysql databases and keep newest $backup_day(config.conf) days backup.
  3. #
  4. # ${db_user} is mysql username
  5. # ${db_password} is mysql password
  6. # ${db_host} is mysql host
  7. # —————————–
  8. #/root/mysql_backup.sh
  9. # everyday 3:00 AM execute database backup
  10. # 0 3 * * * /root/mysql_backup.sh
  11. #/etc/cron.daily
  12. CURRENT_DIR=$(cd "$(dirname "$0")";pwd)
  13. source ${CURRENT_DIR}/config.conf
  14. # the directory for story the newest backup #
  15. test ! -d ${backup_dir} && mkdir -p ${backup_dir}
  16. # 计算忽略表选项
  17. calc_ignore_table()
  18. {
  19. dbname=$1
  20. ignore_table_string=''
  21. for it in ${ignore_table}
  22. do
  23. if [ ${dbname} == ${it%.*} ]
  24. then
  25. ignore_table_string=${ignore_table_string}" --ignore-table ${it}"
  26. fi
  27. done
  28. }
  29. #备份数据库函数#
  30. mysql_backup()
  31. {
  32. # 取所有的数据库名 #
  33. for db in ${all_db}
  34. do
  35. backname=${db}.${time}
  36. dumpfile=${backup_dir}${backname}
  37. ignore_table_string=''
  38. calc_ignore_table ${db}
  39. #将备份的时间、数据库名存入日志
  40. echo "-----"$(date +'%Y-%m-%d %T')" Beginning database "${db}" backup-----" >>${logfile}
  41. ${mysqldump} -F -u${db_user} -h${db_host} -p${db_password} ${ignore_table_string} ${db} > ${dumpfile}.sql 2>>${logfile} 2>&1
  42. #开始将压缩数据日志写入log
  43. echo $(date +'%Y-%m-%d %T')" Beginning zip ${dumpfile}.sql" >>${logfile}
  44. #将备份数据库文件库压成ZIP文件,并删除先前的SQL文件. #
  45. tar -czvf ${backname}.tar.gz ${backname}.sql 2>&1 && rm ${dumpfile}.sql 2>>${logfile} 2>&1
  46. #将压缩后的文件名存入日志。
  47. echo "backup file name:"${dumpfile}".tar.gz" >>${logfile}
  48. echo -e "-----"$(date +'%Y-%m-%d %T')" Ending database "${db}" backup-----\n" >>${logfile}
  49. done
  50. }
  51. delete_old_backup()
  52. {
  53. echo "delete backup file:" >>${logfile}
  54. # 删除旧的备份 查找出当前目录下指定天数前生成的文件,并将之删除
  55. find ${backup_dir} -type f -mtime +${backup_day} | tee delete_list.log | xargs rm -rf
  56. cat delete_list.log >>${logfile}
  57. }
  58. rsync_mysql_backup()
  59. {
  60. # rsync 同步到其他Server中 #
  61. for j in ${web_ip}
  62. do
  63. echo "mysql_backup_rsync to ${j} begin at "$(date +'%Y-%m-%d %T') >>${logfile}
  64. ### 同步 ###
  65. rsync -avz --progress --delete $serverPath -e "ssh -p "${ssh_port}" -i "${id_rsa} ${id_rsa_user}@${j}:$clientPath >>${logfile} 2>&1
  66. echo "mysql_backup_rsync to ${j} done at "$(date +'%Y-%m-%d %T') >>${logfile}
  67. done
  68. }
  69. #进入数据库备份文件目录
  70. cd ${backup_dir}
  71. mysql_backup
  72. delete_old_backup
  73. rsync_mysql_backup
  74. echo -e "============================mysql backup & rsync done at "$(date +'%Y-%m-%d %T')"============================\n\n">>${logfile}
  75. cat ${logfile}