---
title: "分享一个MySQL的备份脚本"
author: "swvip"
date: "2011-03-09T13:34:20Z"
tags: [".net", "Bash", "MySQL", "SQL", "脚本"]
categories: ["数据库"]
slug: "mysql"
draft: false
lastmod: "2011-03-09T13:34:20Z"
id: 948438
url: "https://swvip.iteye.com/blog/948438"
---

CREATE TABLE \`backupinfo\` (  
\`idback\` int(10) unsigned NOT NULL AUTO\_INCREMENT,  
\`start\_time\` timestamp NOT NULL DEFAULT CURRENT\_TIMESTAMP,  
\`end\_time\` datetime DEFAULT NULL,  
\`size\` bigint(20) unsigned DEFAULT NULL,  
\`type\` enum('TEXT','RAW') DEFAULT NULL,  
PRIMARY KEY (\`idback\`)  
) ENGINE=MyISAM AUTO\_INCREMENT=5 DEFAULT CHARSET=latin1;

1 row in set (0.00 sec)

创建一个这样表结构的表用来记录备份的时间的起止时间,以及备份的type,备份文件的大小等等相关的备份信息.

#!/bin/bash

bkDate=\`date +%d%m%Y\` #记录备份时间

bkFolder="/usr/local/mysql/$bkDate/" #选择你备份的存放点,注意你要有在这个目录下写的权限.

mkdir $bkFolder #C创建备份目录

cp /etc/my.cnf $bkFolder #备份你的配置文件

#Flushing the logs and capturing the backup start time.  
#Capturing backup time is just for information.  
#Since this is a textual backup i am storing the backup type as text.

#ToDO: Need to copy the relavent binary logs.

mysql -p -u root -e "FLUSH LOGS;INSERT INTO mysql.backupinfo ( type ) VALUES ( 'TEXT' );" # -u你的备份用户名,-p你的密码

#Taking backup of all databases other that mysql and information\_schema.

for db in \`mysql --skip-column-names -u backup -pBackUp@123 -s -e "SELECT schema\_name FROM information\_schema.SCHEMATA WHERE schema\_name NOT IN ( 'mysql','information\_schema')"\`

do  
mkdir $bkFolder$db; #Creating a new directory for each database.  
mysqldump -d --triggers -u backup -R -E -pBackUp@123 -q --databases $db | gzip &gt; $bkFolder$db/$db.sql.gz #I am using gzip to compress the backup.

done

#Finally I am storing the end time and size of the backup.

mysql -u backup -pBackUp@123 -e "UPDATE mysql.backupinfo SET end\_time = NOW(), size = TRIM(REPLACE(REPLACE('\`du -s\`',' ',''),'.','')) WHERE type = 'TEXT' AND DATE(start\_time) = DATE(NOW())" 

备份的脚本有很多,只是给你再众多之中给你一份更多的选择而已!

 

 

转：[http://blogold.chinaunix.net/u3/116431/showart\_2482944.html](http://blogold.chinaunix.net/u3/116431/showart_2482944.html)