mysql 备份脚本:
--------------------------------------------------------------------------------脚本开始
#设置数据库名,密码,备份路径,日志路径,数据库文件闻之,以及备份方式
#默认的备份方式是tar ,还可以是mysqldump,mysqldoccopy
#默认情况下,用root登录mysql数据库,备份至/root/dbxxxxx.tgz
#!/bin/bash
#This is a ShellScript For Auto DB BackuP
#Powered BY xx
#Setting
DBName=mysql
DBUser=root
DBPasswd=888888
BackupPath=/home/xx/mysql
LogFile=/home/xx/mysql/mysql.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 File !">>$LogFile
fi
if [ -f $NewFile ]
then
echo "[$NewFile] The Back File Is exists,Cann't Backup">>$LogFile
else
case $BackupMethod in
mysqldump)
if [ -z $DBPasswd ]
then
mysqldump -u $DBUser --opt $DBName > $DumpFile
else
mysqldump -u $DBUser -p $DBPasswd -$DBName > $DumpFile
fi
tar czvf $NewFile $DumpFile >> $LogFile 2>&1
echo "[$NewFile] Back up 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 $DumpDFile >> $LogFile 2>&1
fi
tar czvf $NewFile $DumpFile >> $LogFile 2>&1
echo "[$NewFile] Back up Sucess !" >> $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
;;
esac
fi
echo "----------------------------------------" >> $LogFile
----------------------------------------------------------------------------------------------脚本结束----------------------------------------------------------------------------
crontab 定时计划任务添加(/etc/crontab)
00 22 * * * root /home/xx/mysql_backup.sh
备注:刚开始学习写脚本,shell 中 的if后的[]需要加上空格,导致开始调试了很久~