可以將這個腳本放進crontab,每天凌晨執行一次,自動備份這個腳本每天最多只執行一次,而且只保留最近五天的備份在服務器上。
代碼: #!/bin/bash #Setting echo "-------------------------------------------" >> $LogFile if [ -f $NewFile ] echo "-------------------------------------------" >> $LogFile
#This is a ShellScript For Auto DB Backup
#Powered by SearchDatabase
#2005-09
#設置數據庫名,數據庫登錄名,密碼,備份路徑,日志路徑,數據文件位置,以及備份方式
#默認情況下備份方式是tar,還可以是mysqldump,MySQLdotcopy
#默認情況下,用root(空)登錄MySQL數據庫,備份至/root/dbxxxxx.tgz
DBName=MySQL
DBUser=root
DBPasswd=
BackupPath=/root/
LogFile=/root/db.log
DBPath=/var/lib/MySQL/
#BackupMethod=MySQLdump
#BackupMethod=MySQLhotcopy
#BackupMethod=tar
#Setting End
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 $(date +"%y-%m-%d %H:%M:%S") >> $LogFile
echo "--------------------------" >> $LogFile
#Delete Old File
if [ -f $OldFile ]
then
rm -f $OldFile >> $LogFile 2>&1
echo "[$OldFile]Delete Old File Success!" >> $LogFile
else
echo "[$OldFile]No Old Backup File!" >> $LogFile
fi
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 czvf $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 czvf $NewFile $DumpFile >> $LogFile 2>&1
echo "[$NewFile]Backup Success!" >> $LogFile
rm -rf $DumpFile
;;
*)
/etc/init.d/MySQLd stop >/dev/null 2>&1
tar czvf $NewFile $DBPath$DBName >> $LogFile 2>&1
/etc/init.d/MySQLd start >/dev/null 2>&1
echo "[$NewFile]Backup Success!" >> $LogFile
;;
esac
fi