一个Mysql数据库自动备份脚本

 

#!/bin/bash
#This is a ShellScript For Auto DB Backup
#Powered by SearchDatabase
#2005-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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值