MySQL :: Linux 下自动备份数据库的 shell 脚本
Linux 服务器上的程序每天都在更新 MySQL 数据库,于是就想起写一个 shell 脚本,结合
crontab,定时备份数据库。其实非常简单,主要就是使用 MySQL 自带的 mysqldump 命令。
脚本内容如下:
----------------------------------------------------------------------start
#!/bin/sh
# File: /home/mysql/backup.sh
# Database info
DB_NAME="test"
DB_USER="username"
DB_PASS="password"
# Others vars
BIN_DIR="/usr/local/mysql/bin"
BCK_DIR="/home/mysql/backup"
DATE=`date +%F`
# TODO
$BIN_DIR/mysqldump --opt -u$DB_USER -p$DB_PASS $DB_NAME | gzip
> $BCK_DIR/db_$DATE.gz
-----------------------------------------------------------------------------end
然后使用将此脚本加到 /etc/crontab 定时任务中:
01 5 * * 0 mysql /home/mysql/backup.sh
好了,每周日凌晨 5:01 系统就会自动运行 backup.sh 文件备份 MySQL 数据库了。
这个脚本每天最多只执行一次,而且只保留最近五天的备份在服务器上。
第二个方法:
注意:
#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
---------------------------------------------------------------------------------------------end