mysql database backup script

#!/bin/bash

DBName=myql
DBUser=root
DBPasswd=123456
BackupPath=/root/
LogFile=/root/db.log
DBPath=/var/lib/mysql/
NewFile=”$BackupPath”db$(date + %Y%m%d).tgz
DumpFile=”$BackupPath”db(date + %Y%m%d)
OldFile=”$BackupPath”db(date +%Y%m%d –date=’5 days ago’).tgz

echo “——————————————-” >> $LogFile
echo $(date +”%y-%m-%d %H:%M:%S”) >> $LogFile
echo “————————–” >> $LogFile

if [ -f $OldFile ]
then
rm -rf $OldFile >>$LogFile 2>&1
echo “[$OldFile]Delete Old File Success!” >> $LogFile
else
echo “[$OldFile]No Old Backup File!” >> $LogFile
fi

if [ -f $NewFile ]
then
echo “[$NewFile]The Backup File is exists,Can’t Backup!” >> $LogFile
else
case $BackupMethod in
mysqldump)
if [ -z $DBPasswd ]
then
    mysqldump -u $DBUser –opt $DBName >$DumpFile
else
    mysqldump -u $DBUser -p$DBPasswd –opt $DBName >$DumpFile
fi
tar -cvzf $NewFile $DumpFile >> $LogFile 2>&1
echo “[$NewFile]Backup Success!” >> $LogFile
rm -rf $DumpFile
;;
mysqlhotcopy)
rm -rf $DumpFile
mkdir $DumpFile
if [ -z $DBPasswd]
then
    mysqlhotcopy -u $DBUser $DBName $DumpFile >>$LogFile 2>&1
else
    mysqlhotcopy -u $DBUser -p$DBPasswd $DBName $DumpFile >>$LogFile 2>&1
fi
tar -cvzf $NewFile $DumpFile >> $LogFile 2>&1
echo “[$NewFile]Backup Success!” >> $LogFile
rm -rf $DumpFile
;;
*)
/etc/init.d/mysqld stop >/dev/null 2>&1
tar cvzf $NewFile $DBPath$DBName >>$LogFile 2>&1
/etc/init.d/mysqld start >/dev/null 2>&1
echo “[$NewFile]Backup Success!” >> $LogFile
;;
esac
fi

echo “——————————————-” >> $LogFile

Leave a Reply

Your email address will not be published. Required fields are marked *