一、实现分库备份:
#!/bin/bash
#分库备份
bak_user=root-----------备份用户
bak_password=513721ykp--------备份密码
bak_path=/backup/db_bak---------备份路径
bak_cmd="-u$bak_user -p$bak_password"-------登录命令,以便后面重复编写
exc_db="Database|information_schema|mysql|performance_schema|sys"----系统自带的数据库
dbname=`mysql $bak_cmd -e "show databases"| egrep -v $exc_db` --------过滤这些数据库后需要备份的数据库
#echo $bak_db ---如果不放心可以先查看一下
for db in `echo $dbname` -----定义变量db在dbname中循环
do
[ -d $bak_path ] || mkdir -p $bak_path -----若路径不存在则创建路径
mysqldump $bak_cmd -B $db | gzip > $bak_path/${db}_`date +$Y%m%d`.sql.gz ---分库备份
done
二、实现分表备份:
#!/bin/bash
bak_user=root
bak_password=513721ykp
bak_path=/backup
bak_cmd="-u$bak_user -p$bak_password"
exc_db="Database|information_schema|mysql|performance_schema|sys"
db_name=`mysql $bak_cmd -e "show databases"| egrep -v $exc_db`
#echo $db_name
for db in `echo $db_name`
do
[ -d ${bak_path}/dtbak_$db ] || mkdir -p ${bak_path}/dtbak_$db
dt_name=`mysql $bak_cmd -e "use $db;show tables" | egrep -v "Tables_in_$db"`
#echo $db
#echo $dt_name
for dt in `echo $dt_name`
do
#echo $db $dt
mysqldump $bak_cmd $db ${dt} | gzip > $bak_path/dtbak_${db}/${db}_${dt}.`date +%F%m%d`.sql.gz
done
done
-----过程和分库一致,只是最后在循环中嵌套一个表的循环
运行脚本,检查是否备份成功:
在/backup路径下查看(路径可以自己定义位置)
zcat Test_employee.2023-07-290729.sql.gz
查看一下是否有备份的内容:
成功!