MySQL數據庫的備份與恢復(6)——編寫一個mysqldump分表備份腳本
編寫一個腳本,用於備份某個數據庫中所有的數據表,每個數據表生成一個sql文件。
step1、取出hist數據庫包含的所有表的名稱
[root@Mysql11 tmp]# mysql -uroot -p123456 hist -e "show tables;"
mysql: [Warning] Using a password on the command line interface can be insecure.
+----------------+
| Tables_in_hist |
+----------------+
| course |
| dept |
| score |
| stu |
| t1 |
+----------------+
step2、過濾掉標題行
[root@Mysql11 tmp]# mysql -uroot -p123456 hist -e "show tables;"|grep -Evi "table"
mysql: [Warning] Using a password on the command line interface can be insecure.
course
dept
score
stu
t1
step3、編寫腳本
vim backup_tables.sh
腳本的內容如下:
### 利用for循環取出數據庫中所有的表名稱,具體的原理參見step1和step2
for tablename in `mysql -uroot -p123456 hist -e "show tables;"|grep -Evi "table"`
do
### 針對每個表名稱生成相應的mysqldump命令
mysqldump -uroot -p123456 --events hist $tablename|gzip > /tmp/${tablename}_bak.sql.gz
done
step4、爲腳本增加可執行權限
[root@Mysql11 tmp]# pwd
/tmp
[root@Mysql11 tmp]# chmod +x backup_tables.sh
[root@Mysql11 tmp]# ll
總用量 4
-rwxr-xr-x. 1 root root 184 7月 2 15:37 backup_tables.sh
step5、執行腳本,查看執行結果
[root@Mysql11 tmp]# ./backup_tables.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.
mysqldump: [Warning] Using a password on the command line interface can be insecure.
[root@Mysql11 tmp]# ls
backup_tables.sh course_bak.sql.gz dept_bak.sql.gz score_bak.sql.gz stu_bak.sql.gz t1_bak.sql.gz