一个Mysql自动备份脚本
2024-07-24 12:54:56
供稿:网友
可以将这个脚本放进crontab,每天凌晨执行一次,自动备份
这个脚本每天最多只执行一次,而且只保留最近五天的备份在服务器上。
代码:
#!/bin/bash
#this is a shellscript for auto db backup
#powered by aspbiz
#2004-09
#setting
#设置数据库名,数据库登录名,密码,备份路径,日志路径,数据文件位置,以及备份方式
#默认情况下备份方式是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 "-------------------------------------------" >> $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
echo "-------------------------------------------" >> $logfile