#/bin/bash
#This script backup mysqld data.edit badboy,connect leezhenhua17@163.com
user=root
host=localhost
passwd=123456
database=mysql
bak_dir=/backup/${database}
DATE=`date '+%Y%m%d'`
logfile=/backup/log/${DATE}.log
C_DATE=`date "-d 7 day ago" '+%Y%m%d'`
MYSQL="mysql -u${user} -p$passwd -h $host $database"
echo "================================================" >>$logfile
echo "= `date '+%Y-%m-%d %H:%M:%S'`" >>$logfile
#database tables
i=1
tables=($(${MYSQL} -A -Bse "show tables"))
tab_num=`echo ${#tables[@]}`
for arg in ${tables[@]}
do
if [ $i -eq $tab_num ]
then
echo $arg|awk '{print $1,"read"}' >>/tmp/tables
else
echo $arg|awk '{print $1,"read,"}' >>/tmp/tables
fi
i=$(($i+1))
done
lock_tables=`cat /tmp/tables|awk '{printf("%s",$0)}'`
echo "`date '+%Y-%m-%d %H:%M:%S'` start backup database $database" >> $logfile
$MYSQL -A -Bse "lock table $lock_tables ;system cp -r "'/data/mysql'" "'/backup/'";" >>$logfile 2>&1
#echo $?
if [ $? -eq 0 ]
then
echo "`date '+%Y-%m-%d %H:%M:%S'`Backup $database successed" >> $logfile
cd /backup
if [ -d ${database}${DATE} ]
then
echo "`date '+%Y-%m-%d %H:%M:%S'` ${database}${DATE} is exist" >> $logfile
else
mv $database ${database}${DATE}
echo "`date '+%Y-%m-%d %H:%M:%S'` del useless file" >> $logfile
rm -rf /tmp/tables
cd /backup/${database}${DATE}
rm -rf im* cdr* oplog*
fi
else
echo "`date '+%Y-%m-%d %H:%M:%S'` Backup $database Failed" >> $logfile
fi
cd /backup
if [ -d $database${C_DATE} ]
then
echo "`date '+%Y-%m-%d %H:%M:%S'` $database database exist" >> $logfile
tar -zcvf $database${C_DATE}.tar $database >> $logfile 2>&1
echo "`date '+%Y-%m-%d %H:%I:%S'` Delete 7 days before the data $database " >> $logfile
rm -rf $database
else
echo "`date '+%Y-%m-%d %H:%I:%S'` $database${C_DATE} not exist" >> $logfile
fi