#!/bin/bash
#ken.zhang
#This script is used to backup mysql databases on localhost
#set -x
umask 077
BackupPath=/root/bak
LogFile=$BackupPath/BackupLog.log
User=root
Password=XXXXX
# Create directory for each day
mkdir $BackupPath/$(date +%Y%m%d)
# Backup each database into different file
echo "----$(date +%F\ %T)----" >> $LogFile
for i in $(/usr/local/mysql/bin/mysql -u$User -p$Password -e "show databases\G"|grep Database|grep -v 'test'|awk -F: '{print $2}')
do
newBackup=$BackupPath/$(date +%Y%m%d)/$i.sql
if [ -f $newBackup ]
then
echo "Target File $i exists,Backup $i terminated">>$LogFile
continue
else
# echo $i
# echo "-------Backup database $i In Process-------">>$LogFile
/usr/local/mysql/bin/mysqldump -u$User -p$Password $i >$newBackup 2>>$LogFile
if [ $? -eq 0 ];then
echo "Backup $i is successful">>$LogFile
else echo "Bakcup $i faied,check log file for details!">>$LogFile
fi
fi
done
echo "========================================">>$LogFile
cd $BackupPath
# zip up folders.
tar czvf $(date +%Y%m%d).tgz $(date +%Y%m%d) >& /dev/null
# delete folders which are 7 days old
find . -type d -mtime +7|awk -F'/' '{print $2}'|xargs rm -rf {} \;