创建目录
mkdir /server/scripts
一、使用脚本实现分库备份
1、创建脚本并编写
[root@localhost scripts]# vim bak_db_v1.sh +
#!/bin/bash
#########################################
# File Name:bak_db_v1.sh
# Version: V1.0
# Author:Shen QL
# Email:17702390000@163.com
# Organization:
# Create Time:2023-07-27 19:21:21
# Description:分库备份
#########################################
#优化
#备份的路径
bak_path=/backup/db
#账号,密码
mysql_cmd='-uroot -pRedHat@123'
#需要排除的数据库
exclude_db='information_schema|mysql|performance_schema|sys'
#检验备份路径是否存在,不存在则创建
[ -d ${bak_path} ] || mkdir -p ${bak_path}
#提取需要备份的数据库,并将其写入文件(dbname)中
mysql ${mysql_cmd} -e 'show databases' -N | egrep -v "${exclude_db}" > dbname
#循环文件,针对每个库进行备份
while read line
do
mysqldump ${mysql_cmd} -B $line | gzip > ${bak_path}/${line}_$(date +%F).sql.gz
done < dbname
#删除临时文件
rm -f dbname
结果
二、使用脚本实现分表备份
#!/bin/bash
#########################################
# File Name:bak_tb_v1.sh
# Version: V1.0
# Author:Shen QL
# Email:17702390000@163.com
# Organization:
# Create Time:2023-07-27 19:21:21
# Description:分表备份
#########################################
#优化
#备份的路径
bak_path=/backup/db
#账号,密码
mysql_cmd='-uroot -pRedHat@123'
#需要排除的数据库
exclude_db='information_schema|mysql|performance_schema|sys'
#提取需要备份的数据表,并将其写入文件(tbname)中
mysql -uroot -pRedHat@123 -N -e'show tables from abc' > tbname
#循环文件,针对每个表进行备份
while read line
do
#将数据表放在对应的数据库下面
[ -d ${bak_path}/abc ] || mkdir -p ${bak_path}/abc
mysqldump ${mysql_cmd} abc $line | gzip > ${bak_path}/abc/abc_${line}_$(date +%F).sql.gz
done < tbname
#删除临时文件
rm -f tbname
结果
三、使用脚本实现分库分表备份
#!/bin/bash
#########################################
# File Name:bak_tb_v1.sh
# Version: V1.0
# Author:Shen QL
# Email:17702390000@163.com
# Organization:
# Create Time:2023-07-27 19:21:21
# Description:分库分表备份
#########################################
#优化
#备份的路径
bak_path=/backup/db
#账号,密码
mysql_cmd='-uroot -pRedHat@123'
#需要排除的数据库
exclude_db='information_schema|mysql|performance_schema|sys'
#提取需要备份的数据库,并将其写入文件(dbname)中
mysql ${mysql_cmd} -e 'show databases' -N | egrep -v "${exclude_db}" > dbname
while read line
do
#循环文件,针对每个库进行备份
[ -d ${bak_path}/$line ] || mkdir -p ${bak_path}/$line
mysqldump ${mysql_cmd} -B $line | gzip > ${bak_path}/${line}/${line}_$(date +%F).sql.gz
#提取需要备份的数据表,并将其写入文件(tbname)中
mysql ${mysql_cmd} -N -e "show tables from $line" > tbname
#循环文件,针对每个表进行备份
while read tb
do
#将数据表放在对应的数据库下面
mysqldump ${mysql_cmd} $line $tb | gzip > ${bak_path}/$line/${line}_${tb}_$(date +%F).sql.gz
done < tbname
done < dbname
#删除临时文件
rm -f dbname tbname
结果