MYSQL备份脚本(支持备份多个数据库)

用于备份MYSQL数据库的备份脚本,支持备份多个数据库,注意的是数据库需要统一的前缀。没有什么废话详情查看下面内容。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/usr/bin/env bash
# Date : 2020-04-28 18:33:57
# Author : master (master95271@protonmail.com)
# Link : https://www.gov-cn.cn/about
# Introduction: MYSQL Database Backup Script
# PS: Database with multiple uniform prefixes can be backed up, for example: prod_sql1, prod_sql2

MYSQL_HOST="mysql_ip"
MYSQL_USER="backup_user"
MYSQL_PWD="user_passwd"
MYSQL_DB="backup_databases"

gzip="/bin/gzip -9 "
date=`/bin/date '+%Y%m%d-%H%M'`
bakdir="/data/mysql_backup/"

if ! which gzip &>/dev/null; then yum install -y gzip;fi

if [ ! -d "$bakdir" ];then
mkdir -p "$bakdir"
fi

for db_name in `mysql -h${MYSQL_HOST} -u${MYSQL_USER} -p${MYSQL_PWD} -e "show databases;" | grep ${MYSQL_DB}`
do
mysqldump -h${MYSQL_HOST} -u${MYSQL_USER} -p${MYSQL_PWD} $db_name | $gzip > $bakdir/$db_name-$date.sql.gz
done

# Delete more than 10 days
/usr/bin/find ${bakdir} -mtime +10 -exec rm -rf {} \;

echo "Done..."