#!/bin/bash
DBname=lelaohui
backup_dir=/opt/mysqlbackup
dbrootpwd=lelaohui
expired_days=15
LogFile=$backup_dir/db.log
DumpFile=$backup_dir/DB_$DBname_$(date +%Y%m%d_%H).sql
NewFile=$backup_dir/DB_$DBname_$(date +%Y%m%d_%H).tgz
OldFile=$backup_dir/DB_$DBname_$(date +%Y%m%d --date="$expired_days days ago")*.tgz
[ ! -e "$backup_dir" ] && mkdir -p $backup_dir
DB_tmp=`/usr/bin/mysql -uroot -p$dbrootpwd -e "show databasesG" | grep $DBname`
[ -z "$DB_tmp" ] && { echo "`date +%Y%m%d_%H`: [$DBname] not exist" >> $LogFile ; exit 1 ; }
#if [ -n "`ls $OldFile 2>/dev/null`" ];then
# /bin/rm -f $OldFile
# echo "[$OldFile] Delete Old File Success" >> $LogFile
#else
# echo "[$OldFile] Delete Old Backup File" >> $LogFile
#fi
if [ -e "$NewFile" ];then
echo "`date +%Y%m%d_%H`: [$NewFile] The Backup File is exists, Can't Backup" >> $LogFile
else
/usr/bin/mysqldump -uroot -p$dbrootpwd --opt --databases $DBname > $DumpFile
cd $backup_dir
tar czf $NewFile ${DumpFile##*/} >> $LogFile 2>&1
echo "`date +%Y%m%d_%H`: [$NewFile] Backup success ">> $LogFile
/bin/rm -f $DumpFile
fi