#!/bin/bash
#全備方式,一般在從機上執(zhí)行,適用于小中型mysql數據庫
#刪除15天以前備份
#作者:fafu_li
#時間:2015.08.10
source /etc/profile #加載系統(tǒng)環(huán)境變量
source ~/.bash_profile #加載用戶環(huán)境變量
set -o nounset #引用未初始化變量時退出
#set -o errexit #執(zhí)行shell命令遇到錯誤時退出
user="root"
password="123456"
host="localhost"
port="3306"
#需備份的數據庫,數組
db=("test")
#備份時加鎖方式,
#MyISAM為鎖表--lock-all-tables,
#InnoDB為鎖行--single-transaction
lock="--single-transaction"
mysql_path="/usr/local/mysql"
backup_path="${mysql_path}/backup"
date=$(date +%Y-%m-%d_%H-%M-%S)
day=15
backup_log="${mysql_path}/backup.log"
#建立備份目錄
if [ ! -e $backup_path ];then
mkdir -p $backup_path
fi
#刪除以前備份
find $backup_path -type f -mtime +$day -exec rm -rf {} \; > /dev/null 2>1
echo "開始備份數據庫:${db[*]}"
#備份并壓縮
backup_sql(){
dbname=$1
backup_name="${dbname}_${date}.sql"
#-R備份存儲過程,函數,觸發(fā)器
mysqldump -h $host -P $port -u $user -p$password $lock --default-character-set=utf8 --flush-logs -R $dbname > $backup_path/$backup_name
if [[ $? == 0 ]];then
cd $backup_path
tar zcpvf $backup_name.tar.gz $backup_name
size=$(du $backup_name.tar.gz -sh | awk '{print $1}')
rm -rf $backup_name
echo "$date 備份 $dbname($size) 成功 "
else
cd $backup_path
rm -rf $backup_name
echo "$date 備份 $dbname 失敗 "
fi
}
#循環(huán)備份
length=${#db[@]}
for (( i = 0; i $length; i++ )); do
backup_sql ${db[$i]} >> $backup_log 2>1
done
echo "備份結束,結果查看 $backup_log"
du $backup_path/*$date* -sh | awk '{print "文件:" $2 ",大小:" $1}'