#!/bin/bash
#mysql全备脚本,此脚本可以备份多个数据库,
#为每个数据建立单独的文件夹进行备份


#author:yxy
#website:www.sql8.net
#mail:anybooks@qq.com
#created:2014-8-14


#Mysql dabase information
#主机
db_host="localhost"
#数据库帐号
db_user="root"
#数据库密码
db_passwd="12356789"
#mysql安装目录
MYSQL="/opt/lampp/bin/mysql"
#mysql命令目录
MYSQLDUMP="/opt/lampp/bin/mysqldump"




#Path information
#存放备份文件的路径
BACKUP_DB="/opt/backup/database"
LogFile=$BACKUP_DB"/bak.log"


#Time information
#时间
time=`date +"%Y-%m-%d-%H-%M-%S"`
day=`date +"%d"`
month=`date +"%Y-%m"`
weekday=`date +"%u"`






#Path enable write
if [ ! -w "$BACKUP_DB" ]; then
chmod -R 700 $BACKUP_DB
fi


#echo "**********************************host info****************************************"
#echo "db_host:"$db_host
#echo "db_user:"$db_user
#echo "db_passwd:"$db_passwd
#echo "MYSQL:"$MYSQL
#echo "MYSQLDUMP:"$MYSQLDUMP
#echo "databaseName:"$databaseName
#echo "BACKUP_DB:"$BACKUP_DB
#echo "**********************************************************************************"




#Mysql Backup
Date=`date +%Y%m%d`
Begin=`date +"%Y-%m-%d %H:%M:%S"`
#echo "start backup database:"$databaseName"   "$Begin


#databases
#需要备份的数据库,如果有多个数据库,请用,分隔
databaseList="dd1,dd2"
for databaseName in `echo "$databaseList" | sed 's/,/\n/g'`
do  
    echo $databaseName


#fileName
#生成备份文件名
fileName=$databaseName"-"$time".sql"
#生成备份文件完整路径
BACKUP_DBPATH=$BACKUP_DB"/"$databaseName




#echo "***********************************database Info***********************************************"
#echo "BACKUP_DBPATH:"$BACKUP_DBPATH
#echo "fileName:"$fileName
#echo "**********************************************************************************"


 


if [ ! -d "$BACKUP_DBPATH" ]; then
mkdir "$BACKUP_DBPATH" 
fi
#备份mysql
$MYSQLDUMP -u $db_user -p$db_passwd -h $db_host $databaseName > $BACKUP_DBPATH/$fileName
#打包.sql文件
cd $BACKUP_DBPATH && tar -czf $fileName.tar.gz $fileName && rm -rf $fileName && chmod go-rwx $fileName.tar.gz


Last=`date +"%Y-%m-%d %H:%M:%S"`
#echo "end backup database:"$databaseName"   "$Last
#输出日志
echo start:$Begin end:$Last $fileName succ >> $LogFile
#关于备份文件,本脚本不作处理,如果有需要可以联系楼主
done