Linux下MySQL数据库备份脚本

1.首先建立sh文件,在/usr/bin/先建立一个名叫mysqlscript.sh的脚本文件,内容参见mysqlscript.sh

2.其次在根目录下打开 #crontab -e 输入以下内容 12 12 * * * /usr/bin/mysqlscript.sh

3.最后,如果发现不能定时执行脚本,可能的原因是mysqlscript.sh脚本文件的权限问题,然后更改为可执行文件#chmod 777 mysqlscript.sh;

4.上面的工作做完以后就应该没什么问题.
mysqlscript.sh的脚本内容如下:

#!/bin/bash
#This is a ShellScript For Auto DB Backup
#Powered by aspbiz
#2007-11-25


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

相关推荐