linux 定期自动备份mysql的shell

jerry mysql 2015年11月23日 收藏

数据无价,及时备份 刚才有个玩家在站上玩游戏,提醒了我要及时备份数据啊,万一哪天服务器挂了把他们的数据丢了,我可就是罪人了! 一直打算放个自动备份的shell,都没有放。正好现在不忙,随手加了进去。 安全起见,直接用Root执行的: /root/mysql_backup.sh

# everyday 3:00 AM execute database backup 3 0 * * * /root/mysql_backup.sh

以下是自动自动备份shell,只保留最新5天

  1. #!/bin/sh
  2. # mysql_backup.sh: backup mysql databases and keep newest 5 days backup.
  3. #
  4. # db_user is mysql username
  5. # db_passwd is mysql password
  6. # db_host is mysql host
  7. # —————————–
  8. db_user="root"
  9. db_passwd="zhoz.com"
  10. db_host="localhost"
  11. # the directory for story your backup file.
  12. backup_dir="/home/zhozdbbackup"
  13. # date format for backup file (dd-mm-yyyy)
  14. time="$(date +"%d-%m-%Y")"
  15. # mysql, mysqldump and some other bin's path
  16. MYSQL="/usr/bin/mysql"
  17. MYSQLDUMP="/usr/bin/mysqldump"
  18. MKDIR="/bin/mkdir"
  19. RM="/bin/rm"
  20. MV="/bin/mv"
  21. GZIP="/bin/gzip"
  22. # check the directory for store backup is writeable
  23. test ! -w $backup_dir && echo "Error: $backup_dir is un-writeable." && exit 0
  24. # the directory for story the newest backup
  25. test ! -d "$backup_dir/backup.0/" && $MKDIR "$backup_dir/backup.0/"
  26. # get all databases
  27. all_db="$($MYSQL -u $db_user -h $db_host -p$db_passwd -Bse 'show databases')"
  28. for db in $all_db
  29. do
  30. $MYSQLDUMP -u $db_user -h $db_host -p$db_passwd $db | $GZIP -9 > "$backup_dir/backup.0/$time.$db.gz"
  31. done
  32. # delete the oldest backup
  33. test -d "$backup_dir/backup.5/" && $RM -rf "$backup_dir/backup.5"
  34. # rotate backup directory
  35. for int in 4 3 2 1 0
  36. do
  37. if(test -d "$backup_dir"/backup."$int")
  38. then
  39. next_int=`expr $int + 1`
  40. $MV "$backup_dir"/backup."$int" "$backup_dir"/backup."$next_int"
  41. fi
  42. done
  43. exit 0;