MySQL數據庫的備份與恢復(5)——編寫一個簡單的mysqldump分庫備份腳本
編寫一個腳本,用於備份除了information_schema和performance_schema數據庫之外的所有數據庫,每個數據庫生成一個sql文件。
step1、取出MySQL包含的所有數據庫名稱
[root@Mysql11 tmp]# mysql -uroot -p123456 -e "show databases;"
mysql: [Warning] Using a password on the command line interface can be insecure.
+--------------------+
| Database |
+--------------------+
| information_schema |
| hist |
| mysql |
| performance_schema |
| sys |
| wanggx |
+--------------------+
step2、過濾掉系統數據庫和標題行
[root@Mysql11 tmp]# mysql -uroot -p123456 -e "show databases;"|grep -Evi "database|information|performance"
mysql: [Warning] Using a password on the command line interface can be insecure.
hist
mysql
sys
wanggx
step3、編寫腳本
vim backup.sh
腳本的內容如下:
### 利用for循環取出所有的數據庫名稱,具體的原理參見step1和step2
for dbname in `mysql -uroot -p123456 -e "show databases;"|grep -Evi "database|infor|perfor"`
do
### 針對每個數據庫名稱生成相應的mysqldump命令
mysqldump -uroot -p123456 --events -B $dbname|gzip > /tmp/${dbname}_bak.sql.gz
done
step4、爲腳本增加可執行權限
[root@Mysql11 tmp]# pwd
/tmp
[root@Mysql11 tmp]# vim backup.sh
[root@Mysql11 tmp]# chmod +x backup.sh
[root@Mysql11 tmp]# ll
總用量 4
-rwxr-xr-x. 1 root root 184 7月 2 15:09 backup.sh
step5、執行腳本,查看執行結果
[root@Mysql11 tmp]# ./backup.sh
mysql: [Warning] Using a password on the command line interface can be insecure.
mysqldump: [Warning] Using a password on the command line interface can be insecure.
mysqldump: [Warning] Using a password on the command line interface can be insecure.
mysqldump: [Warning] Using a password on the command line interface can be insecure.
mysqldump: [Warning] Using a password on the command line interface can be insecure.
[root@Mysql11 tmp]# ls
backup.sh hist_bak.sql.gz mysql_bak.sql.gz sys_bak.sql.gz wanggx_bak.sql.gz