Skip to content

Instantly share code, notes, and snippets.

@moolex
Created December 3, 2012 10:35
Show Gist options
  • Save moolex/4194125 to your computer and use it in GitHub Desktop.
Save moolex/4194125 to your computer and use it in GitHub Desktop.
mysql 数据库自动热备份脚本(centos+mysqlhotcopy)
#!/bin/sh
# Moyo <dev@uuland.org> @ 2012/02/22 10:00
# @url http://moyo.uuland.org/system/mysqlhotcopy-auto-sh/
# DEFINED ~~
# 需要备份的数据库列表(空格间隔)
dbns="mysql"
# 备份目录
dbsf=/home/backup/database
# notify MAIL
smail="server.moyo@gmail.com"
# from MAIL
fmail="server@cenwor.com"
# 备份保存时间(天)
dbkeepd=7
# mysqlhotcopy 位置
mysqlhotcopy=/usr/local/mysql/bin/mysqlhotcopy
# backup start
cdate=`date "+%Y.%m.%d"`
ii=0
tsa=0
tmplog="$dbsf/$cdate.ops.log"
for dbn in $dbns; do
# ~~
bakdirbase="$dbsf/$dbn"
if [ ! -e $bakdirbase ]
then
mkdir -p $bakdirbase
fi
pkgfile="$bakdirbase/$cdate.tar.gz"
if [ -e $pkgfile ]
then
echo "$dbn has been backuped. [$pkgfile]" >> $tmplog
else
ii=`expr $ii + 1`
# mk dir
bakdircur="$bakdirbase/$cdate"
if [ ! -e $bakdircur ]
then
mkdir -p $bakdircur
echo "moyo" > "$bakdircur/rm.lock"
fi
# start
time_start=`date "+%s"`
# s1 : backup
$mysqlhotcopy $dbn --addtodest $bakdircur
# s2 : package
tar czf $pkgfile -C $bakdircur $dbn
# s3 : rm dir
if [ -e $bakdircur/rm.lock ]
then
rm -rf $bakdircur
fi
# time calc
time_stop=`date "+%s"`
time_use=`expr $time_stop - $time_start`
echo "$dbn backup && package finish / use $time_use (s)" >> $tmplog
tsa=`expr $tsa + $time_use`
# delete old backups
echo "---" >> $tmplog
echo "detecting if old backups..." >> $tmplog
find $bakdirbase -type f -mtime +$dbkeepd -name "*.tar.gz" -exec rm -f {} \; >> $tmplog
fi
echo "--- === ---" >> $tmplog
# ~~
done
# send mail
msubject="[ "`date "+%Y-%m-%d"`" ] database ($ii) backuped | use $tsa (s)"
cat $tmplog | mail -s "$msubject" $smail -- -f $fmail
rm -f $tmplog
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment