mysql数据库shell备份脚本

任何项目的运行都离不开数据,持久化数据对于一个企业尤为重要,任何时候都不可掉以轻心,下面是我自己写的一个shell脚本,用来备份数据,分享给大家。

#!/bin/bash
# 数据库连接信息
MY_user=""
MY_pass=""
MY_port="3306"

# 环境变量
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:/data/mysql_57/bin
export PATH
MY_data=`date "+%F"`

# 脚本日志
SHELL_LOG="/root/mysql_bak.sh.log"

# mysql 目录
Mysql_datadir="/data/mysql_57"
Mysql_Binlog_dir="/data/mysql_57/logs/bin-log"

# 备份目录
Bak_dir="/root/mysql_data"
Full_dir=${Bak_dir}/full  # 全量备份目录
DB_dir=${Bak_dir}/db  # 单库备份目录
Binlog_dir=${Bak_dir}/binlog  # 增量二进制备份目录

# Write Log 
shell_log(){
    LOG_INFO=$1
    echo "$(date "+%F") $(date "+%T") : $0 : ${LOG_INFO}" >> ${SHELL_LOG}
}
case $1 in
# 全量备份
Full)
    mysqldump -u${MY_user} -p${MY_pass} -P${MY_port} -A -B -F -R -x --events|gzip > ${Full_dir}/${MY_data}_all.sql.gz
    if [[ $? -eq 0 ]];then
        shell_log "SUCCESS: mysql Full database bak is success"
    else
        shell_log "ERROR: mysql Full database bak error"
    fi
;;
# 单库备份
db)
	db_fun(){
	    DB_name=$1
        mysqldump -u${MY_user} -p${MY_pass} -P${MY_port} -F -B  ${DB_name}|gzip > ${DB_dir}/${MY_data}_${DB_name}.sql.gz
        if [[ $? -eq 0 ]];then
            shell_log "SUCCESS: mysql database ${DB_name} bak is success"
        else
            shell_log "ERROR: mysql database ${DB_name} bak error"
        fi
	}
	db_fun cadavertrace
;;
# 增量备份(全量和单库备份都会刷新二进制日志)
increment)
	cd ${Mysql_Binlog_dir}
	binlog=`ls -At mysql-bin* | head -n 1`
	gzip -c ${binlog} > ${Binlog_dir}/${binlog}.gz
	mysql -u${MY_user} -p${MY_pass} -P${MY_port} -e "flush logs;" 2> /dev/null
;;
*)
	echo "ERROR: Usage: mysqlbak [ Full | db | increment ]"
;;
esac
#if [[ $# -eq 0 ]];then
#	echo "Invalid paramete;Full | db | increment"	
#fi