=======================================================================
shell自动化脚本实战---备份
=======================================================================
数据库备份: 结合计划任务 MySQL、 Oracle
网站备份: tar,异地保存--ftp、rsync
一、数据库备份
1.利用自带工具mysqldump 实现数据库分库备份
分库备份:
1> 如何获取备份的数据库列表
[root@localhost mysql-5.7.18]# DBS=`mysql -uroot -p'123456' -N -e 'show databases' | egrep -v "information_schema|mysql|performance_schema|sys"`
mysql: [Warning] Using a password on the command line interface can be insecure.
[root@localhost mysql-5.7.18]# echo $DBS
2> 循环遍历
for db in $DBS
do
echo 备份 $db
done
3> 备份语句实现
[root@localhost ~]# mysqldump -uroot -p'123456' -B $db > $db.sql
优化:
[root@localhost ~]# mysqldump -uroot -p'123456' -B user > user_$(date +%F).sql
分库备份参考代码:
#!/bin/bash
#define var
BAK_DIR=/backup/db
CMD_OPT="-uroot -p123456"
EX_DB="information_schema|mysql|performance_schema|sys"
DBS=$(mysql ${CMD_OPT} -N -e 'show databases' | egrep -v ${EX_DB})
# main program
[ -d ${BAK_DIR} ] || mkdir -p ${BAK_DIR}
for db in $DBS
do
mysqldump ${CMD_OPT} -B $db > ${BAK_DIR}/${db}_$(date +%F).sql
done
2、分表
mysql -uroot -p'123456' -N -e 'show tables from user'
#!/bin/bash
#define var
BAK_DIR=/backup/db
CMD_OPT="-uroot -p123456"
db=user
TABS=$(mysql ${CMD_OPT} -N -e "show tables from $db")
# main program
[ -d ${BAK_DIR}/$db ] || mkdir -p ${BAK_DIR}/$db
for tab in $TABS
do
mysqldump ${CMD_OPT} $db $tab > ${BAK_DIR}/$db/${db}_$tab_$(date +%F).sql
3、分库分表
#define var
BAK_DIR=/backup/db
CMD_OPT="-uroot -p123456"
EX_DB="information_schema|mysql|performance_schema|sys"
DBS=$(mysql ${CMD_OPT} -N -e 'show databases' | egrep -v ${EX_DB})
for db in $DBS
do
TABS=$(mysql ${CMD_OPT} -N -e "show tables from $db")
[ -d ${BAK_DIR}/$db ] || mkdir -p ${BAK_DIR}/$db
mysqldump ${CMD_OPT} -B $db > ${BAK_DIR}/${db}_$(date +%F).sql
for tab in $TABS
do
mysqldump ${CMD_OPT} $db $tab > ${BAK_DIR}/$db/${db}_$tab_$(date +%F).sql
done
done
4.优化
优化:
#!/bin/bash
#define var
BAK_DIR=/backup/db
CMD_OPT="-uroot -p123456"
EX_DB="information_schema|mysql|performance_schema|sys"
DBS=$(mysql ${CMD_OPT} -N -e 'show databases' | egrep -v ${EX_DB})
# main program
for db in $DBS
do
TABS=$(mysql ${CMD_OPT} -N -e "show tables from $db")
[ -d ${BAK_DIR}/$db ] || mkdir -p ${BAK_DIR}/$db
mysqldump ${CMD_OPT} -B $db | gzip > ${BAK_DIR}/$db/${db}_$(date +%F).sql.gz
# 分表备份
for tab in $TABS
do
mysqldump ${CMD_OPT} $db $tab | gzip > ${BAK_DIR}/$db/${db}_$tab_$(date +%F).sql.gz
done
done