Loading

mysql备份脚本

#!/bin/bash

#-----------------------------------------------------------------------------
# Author:Bathing
# Function:This script will be used for mysql backups,It was created by Bathing.
# Date:2021-07-22
# QQinfo:576590916
# work on Mysql_5.7
#-----------------------------------------------------------------------------
#设置颜色显示
SETCOLOR_SUCCESS="echo -en \\033[0;32m"
SETCOLOR_FAILURE="echo -en \\033[0;31m"
SETCOLOR_WARNING="echo -en \\033[0;33m"
SETCOLOR_NORMAL="echo -en \\033[0;39m"

#设置登陆变量
MY_USER=""
MY_PASS=""
MY_PORT=""
MY_HOST="localhost"

#mysql安装目录
name=/www/server/mysql

#user
USER=`whoami`

#备份的数据库名,可定义多个数据库,中间以空格隔开,如: (test test1 test2)
dbname=()

#备份路径
backpath=${name}/backup

#备份的时间
DATA=$(date +%Y%m%d-%H%M)

#日志备份路径
logpath=${name}/log

#脚本运行账号为root账户
ACCOUNT_JUDGE_FUN () {

if [ "$(whoami)" != "root" ];then
${SETCOLOR_WARNING} && echo "warning:please use root account install cloudroom system!" && ${SETCOLOR_NORMAL}
exit 1
fi

}
ACCOUNT_JUDGE_FUN

#创建备份路径
mkdir -p ${logpath}
chown -R mysql:mysql ${logpath}
mkdir -p ${backpath}
touch ${logpath}/mysqlbackup.log

#开始备份数据库
for db in ${dbname[*]}; do
mysqldump -u${MY_USER} -h${MY_HOST} -P${MY_PORT} -p${MY_PASS} --single-transaction ${dbname} > ${backpath}/${db}-${DATA}.sql 2>/dev/null
#备份成功以下操作
if [ "$?" == 0 ];then
cd ${backpath}
#备份日志记录
echo ================================================ >> ${logpath}/mysqlbackup.log
echo 备份时间为${DATA},开始备份${db}数据库...>> ${logpath}/mysqlbackup.log
#为节约硬盘空间,将数据库压缩
tar zcf ${db}${DATA}.tar.gz ${db}-${DATA}.sql > /dev/null
#删除原始文件,只留压缩后文件
rm -rf ${backpath}/${db}-${DATA}.sql
echo The mysql database is backed up successfully!! >> ${logpath}/mysqlbackup.log
echo ================================================ >> ${logpath}/mysqlbackup.log
else
#备份失败则进行以下操作
echo Failed to back up the mysql database. Procedure!! >> ${logpath}/mysqlbackup.log
echo ================================================ >> ${logpath}/mysqlbackup.log
fi
done
#保留7天的数据备份

find ${backpath} -mtime +7 -name "*.gz" -exec rm -rf {} \;

 

 

posted @ 2021-08-05 10:48  bathing  阅读(88)  评论(0编辑  收藏  举报
Live2D