在服务器上用shell定时备份mysql
1. 在crontab中加入定时备份任务
20 1 * * * cd /www/tools;/bin/bash /www/tools/back.sh
2. /www/tools/目录下back.sh
dbs=(autohome car content data hangqing manager question saler spider user)
for db in ${dbs[@]}
do
/bin/sh mysql.sh $db
done
3. /www/tools/目录下mysql.sh
#!/bin/bash
#Setting Start
DBName=$1
DBUser=#数据库用户名
DBPasswd=#数据库密码
BackupPath=/data/backup/mysql/ #备份路径
LogFile=/data/logs/backup/db_backup.log #日志路径
DBPath=/usr/bin/mysql #mysql的安装路径
BackupMethod=mysqldump #备份命令
#Setting End
NewFile="$BackupPath"$DBName$(date +%y%m%d).tgz
DumpFile="$BackupPath"$DBName$(date +%y%m%d)
OldFile="$BackupPath"$DBName$(date +%y%m%d --date='5 days ago').tgz
echo "-------------------------------------------" >> $LogFile
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
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 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