linux下mysql自动备份脚本代码

  • A+
所属分类:数据库

mysql是以mysql用户身份运行的,对/home /mybackup不可写也会失败
脚本放在 /home/user/mysql_backup.sh
crontab
# crontab -l
# m h dom mon dow command
28 16 * * * /home/user/mysql_backup.sh
脚本如下

  1. #!/bin/sh   
  2. # mysql_backup.sh: backup mysql databases and keep newest 5 days backup.   
  3. #   
  4. # Last updated: 20 March 2006   
  5. # ----------------------------------------------------------------------   
  6. # This is a free shell script under GNU GPL version 2.0 or above   
  7. # Copyright (C) 2006 Sam Tang   
  8. # Feedback/comment/suggestions : http://www.real-blog.com/   
  9. # ----------------------------------------------------------------------   
  10. # your mysql login information   
  11. # db_user is mysql username   
  12. # db_passwd is mysql password   
  13. # db_host is mysql host   
  14. # -----------------------------   
  15. db_user="root"   
  16. db_passwd="password"   
  17. db_host="localhost"   
  18. # the directory for story your backup file.   
  19. backup_dir="/home/mybackup"   
  20. # date format for backup file (dd-mm-yyyy)   
  21. time="$(date +"%d-%m-%Y")"   
  22. # mysql, mysqldump and some other bin's path   
  23. MYSQL="/usr/local/mysql/bin/mysql"   
  24. MYSQLDUMP="/usr/local/mysql/bin/mysqldump"   
  25. MKDIR="/bin/mkdir"   
  26. RM="/bin/rm"   
  27. MV="/bin/mv"   
  28. GZIP="/bin/gzip"   
  29. # check the directory for store backup is writeable   
  30. test ! -w $backup_dir && echo "Error: $backup_dir is un-writeable." && exit 0   
  31. # the directory for story the newest backup   
  32. test ! -d "$backup_dir/backup.0/" && $MKDIR "$backup_dir/backup.0/"   
  33. # get all databases   
  34. all_db="$($MYSQL -u $db_user -h $db_host -p$db_passwd -Bse 'show databases')"   
  35. for db in $all_db   
  36. do   
  37. $MYSQLDUMP -u $db_user -h $db_host -p$db_passwd $db | $GZIP -9 > "$backup_dir/backup.0/$time.$db.gz"   
  38. done   
  39. # delete the oldest backup   
  40. test -d "$backup_dir/backup.5/" && $RM -rf "$backup_dir/backup.5"   
  41. # rotate backup directory   
  42. for int in 4 3 2 1 0   
  43. do   
  44. if(test -d "$backup_dir"/backup."$int")   
  45. then   
  46. next_int=`expr $int + 1`   
  47. $MV "$backup_dir"/backup."$int" "$backup_dir"/backup."$next_int"   
  48. fi   
  49. done   
  50. exit 0;   

备注:
mysql是以mysql用户身份运行的,对/home /mybackup不可写也会失败
chmod 777 /home/mybackup问题解决了

图片引用自网络