MySQL database backup and recovery (6)-write a mysqldump sub-table backup script

MySQL database backup and recovery (6)-write a mysqldump sub-table backup script

Write a script to back up all data tables in a database, and each data table generates an sql file.

step1, take out the names of all tables contained in the hist database

[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, filter out the header row

[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, write script

vim backup_tables.sh

The content of the script is as follows:

### 利用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, add executable permissions to the script

[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, execute the script, view the execution result

[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

Guess you like

Origin blog.csdn.net/weixin_44377973/article/details/107085696