linux 自动备份mysql ----shell

原地址:http://blogread.cn/it/article/6089?f=wb

安全起见,直接用Root执行的:
/root/mysql_backup.sh

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

以下是自动自动备份shell,

    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.  

    12. # the directory for story your backup file.  

    13. backup_dir="/home/zhozdbbackup"  

    14.  

    15. # date format for backup file (dd-mm-yyyy)  

    16. time="$(date +"%d-%m-%Y")"  

    17.  

    18. # mysql, mysqldump and some other bin's path  

    19. MYSQL="/usr/bin/mysql"  

    20. MYSQLDUMP="/usr/bin/mysqldump"  

    21. MKDIR="/bin/mkdir"  

    22. RM="/bin/rm"  

    23. MV="/bin/mv"  

    24. GZIP="/bin/gzip"  

    25.  

    26. # check the directory for store backup is writeable  

    27. test ! -w $backup_dir && echo "Error: $backup_dir is un-writeable." && exit 0  

    28.  

    29. # the directory for story the newest backup  

    30. test ! -d "$backup_dir/backup.0/" && $MKDIR "$backup_dir/backup.0/"  

    31.  

    32. # get all databases  

    33. all_db="$($MYSQL -u $db_user -h $db_host -p$db_passwd -Bse 'show databases')"  

    34. for db in $all_db  

    35. do  

    36. $MYSQLDUMP -u $db_user -h $db_host -p$db_passwd $db | $GZIP -9 > "$backup_dir/backup.0/$time.$db.gz"  

    37. done  

    38.  

    39. # delete the oldest backup  

    40. test -d "$backup_dir/backup.5/" && $RM -rf "$backup_dir/backup.5"  

    41.  

    42. # rotate backup directory  

    43. for int in 4 3 2 1 0  

    44. do  

    45. if(test -d "$backup_dir"/backup."$int")  

    46. then  

    47. next_int=`expr $int + 1`  

    48. $MV "$backup_dir"/backup."$int" "$backup_dir"/backup."$next_int"  

    49. fi  

    50. done  

    51. exit 0;  

posted @ 2012-12-27 12:07  尹少爷  阅读(219)  评论(0编辑  收藏  举报