#!/bin/bash ## by Mr he bak_dir="/data/mysql_backup/" xtr_path="/usr/bin/innobackupex" mysql_cnf="/etc/my.cnf" thr_cnt=1 name="xxx" pawd="xxx" e_path="/home/mysql/sendEmail.sh" # 备份文件名 cur_path="$bak_dir"`date +%F_%H_%M_%S` ##备份日志 bak_log="/tmp/backup_mysql.txt" ip_addr=`ip a| grep inet|grep -v 127.0.0.1|grep -v inet6|awk ‘{print $2}‘| awk -F ‘/‘ ‘{print $1}‘ |head -1 ` ###判断备份目录 [[ -d $bak_dir ]] || mkdir -p $bak_dir cd $bak_dir function bak_full() { $xtr_path --defaults-file=$mysql_cnf --user=$name --password=$pawd --host=127.0.0.1 --port 3306 --parallel=$thr_cnt --no-timestamp ${cur_path}full > $bak_log 2>&1 ###备份结束时间 bak_end=`sed ‘/^$/d‘ $bak_log | tail -1 | awk {‘print $1"-"$2‘}` ####判断备份是否成功 OK! ok_str=`sed ‘/^$/d‘ $bak_log | tail -1 | awk ‘{print $4}‘ ` bak_sendEmail "$ok_str" } function bak_inc() { #### 获得上次备份的基准目录 prev_dir=`ls -l |awk ‘{print $9}‘|grep -v ‘^$‘ |grep -v .tar | sort |head -1 ` $xtr_path --defaults-file=$mysql_cnf --user=$name --password=$pawd --host=127.0.0.1 --port 3306 --parallel=$thr_cnt --no-timestamp --incremental ${cur_path}inc --incremental-basedir="$bak_dir""$prev_dir" > $bak_log 2>&1 bak_end=`sed ‘/^$/d‘ $bak_log | tail -1 | awk {‘print $1"-"$2‘}` ok_str=`sed ‘/^$/d‘ $bak_log | tail -1 | awk ‘{print $4}‘` bak_sendEmail "$ok_str" } function bak_sendEmail() { if [ "$1" == "OK!" ]; then ###压缩当前备份 file_tar=`ls -l |awk ‘{print $9}‘|grep -v ‘^$‘ |grep -v .tar |sort -n |tail -1 ` tar -zcvf ${file_tar}.tar ${file_tar} > /dev/null 2>&1 #####删除备份基准文件 ## rm -rf `ls -l |grep -v .tar | grep -v $file_tar find ./ -maxdepth 1 -type d ! -name "${file_tar}*" | awk -F ‘/‘ ‘{print $2}‘ | xargs rm -rf #### echo 可改为 $e_path 发的邮件脚本 echo " backup successful" " backup successful IP:$ip_addr bak_str:$bak_str bak_end:$bak_end" else rm -rf $cur_path* ###删除当前备份失败的目录 echo " !!! backup failure !!!" " !!! backup failure !!! IP:$ip_addr $bak_str backup have some wrong!!!" "$bak_log" fi } ###备份开始时间 bak_str=`date +%Y-%m-%d_%H:%M:%S` if [ "$1" == "full" ]; then bak_full elif [ "$1" == "inc" ]; then #####如果备份的目录下没有备份,全备 if [ `find $bak_dir -maxdepth 1 -type d | wc -l` -eq 1 ]; then bak_full else bak_inc fi else echo "Usage: $0 full | inc " exit fi ## 删除2周前的数据备份 rm -rf ${bak_dir}`date -d ‘14 days ago‘ +‘%F‘`_*