MySql备份数据库shell脚本
MySql自动备份数据库脚本
#!/bin/bash
# MySQL登录凭据
MYSQL_USER="root"
MYSQL_PASSWORD="123456"
# 备份目录
BACKUP_LOCATION="/opt/mysql"
# 是否开启过期备份删除 ON为开启 OFF为关闭
EXPIRE_BACKUP_DELETE="ON"
#过期时间天数 默认为三天,此项只有在EXPIRE_BACKUP_DELETE开启时有效
EXPIRE_DAYS=3
# 排除系统自带的数据库
EXCLUDE_DATABASES=("information_schema" "mysql" "performance_schema" "sys")
# 指定需要备份的数据库
BACKUP_DATABASES=("*") # 备份所有数据库
# BACKUP_DATABASES=("DB1" "DB2") # 备份指定数据库
# 以下不需要修改
BACKUP_TIME=`date +%Y%m%d%H%M` #定义备份详细时间(获取当前日期和时间)
BACKUP_Ymd=`date +%Y-%m-%d` #定义备份目录中的年月日时间,mysql2/2023-09-07
BACKUP_DIR=$BACKUP_LOCATION/$BACKUP_Ymd #备份文件夹全路径
WELCOME_Msg="欢迎使用MySQL备份工具!!!" # 欢迎语
# 函数,获取数组是否包含指定元素
function contains() {
local n=$#
local value=${!n}
for ((i=1;i < $#;i++)) {
if [ "${!i}" == "${value}" ]; then
echo "y"
return 0
fi
}
echo "n"
return 1
}
# 判断MYSQL是否启动,没有启动则备份退出
mysql_ps=`ps -ef |grep mysql |wc -l`
mysql_listen=`netstat -an |grep LISTEN |grep $mysql_port|wc -l`
if [ [$mysql_ps == 0] -o [$mysql_listen == 0] ]; then
echo "错误:MYSQL服务没有启动!退出备份!"
exit
else
echo $WELCOME_Msg
fi
# 创建备份目录
if [ ! -d "$BACKUP_DIR" ]; then
mkdir -p "$BACKUP_DIR"
fi
# 设置需要备份的数据库
if [ $(contains "${BACKUP_DATABASES[@]}" "*") == "y" ]; then
echo "备份全部数据库"
BACKUP_DATABASES=$(mysql -u$MYSQL_USER -p$MYSQL_PASSWORD -e "SHOW DATABASES;" | grep -Ev "(Database|${EXCLUDE_DATABASES[*]})");
else
echo "备份指定数据库"
fi
# 临时将BACKUP_DATABASES数组赋值给BACKUP_DATABASES_TEMP
BACKUP_DATABASES_TEMP=("${BACKUP_DATABASES[@]}")
# 清空BACKUP_DATABASES数组,下面会重新赋值,或使用 BACKUP_DATABASES=()清空
unset BACKUP_DATABASES
# 排除不需要备份的数据库
for DATABASE in ${BACKUP_DATABASES_TEMP[@]};
do
# 设置标志来指示是否找到匹配的元素
found=false
for EXCLUDE_DATABASE in ${EXCLUDE_DATABASES[@]};
do
# 如果找到了,则去除该元素
if [ "$DATABASE" == "$EXCLUDE_DATABASE" ]; then
found=true
break
fi
done
# 如果没有找到匹配的元素,将其添加到结果BACKUP_DATABASES数组中
if [ "$found" == false ]; then
BACKUP_DATABASES+=("$DATABASE")
fi
done
# 遍历需要备份的数据库
# for DATABASE in $(mysql -u$MYSQL_USER -p$MYSQL_PASSWORD -e "SHOW DATABASES;" | grep -Ev "(Database|${EXCLUDE_DATABASES[*]})");
for DATABASE in ${BACKUP_DATABASES[@]};
do
BACKUP_FILE="$BACKUP_DIR/$DATABASE-$BACKUP_TIME.sql"
mysqldump -u$MYSQL_USER -p$MYSQL_PASSWORD $DATABASE > $BACKUP_FILE
if [ $? -eq 0 ]; then
echo "备份数据库 $DATABASE 到 $BACKUP_FILE 成功"
# 压缩备份文件
gzip $BACKUP_FILE
if [ $? -eq 0 ]; then
echo "压缩备份文件 $BACKUP_FILE.gz 成功"
else
echo "压缩备份文件 $BACKUP_FILE.gz 失败"
fi
else
echo "备份数据库 $DATABASE 失败"
fi
done
echo "数据库备份完毕!"
# 如果开启了删除过期备份,则进行删除操作
if [ "$EXPIRE_BACKUP_DELETE" == "ON" -a "$BACKUP_LOCATION" != "" ];then
`find $BACKUP_LOCATION/ -type d -mtime +$EXPIRE_DAYS | xargs rm -rf`
echo "删除过期备份成功!"
fi
exit
评论区