#!/bin/bash
#
#desc:simlpe script for mysql daily auto backup,archived every ten days.
#
#create by:xiaozhenggang
#
#date:2011/11/29
#
#update:2011/12/03
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:/usr/local/mysql/bin
export PATH
TMP_BAK_DIR=/tmp/data_bak
BAK_DIR=/data_bak
BAK_DATE=`date +'%Y-%m-%d %H:%M:%S'`
BAK_USER=backup
BAK_PASSWD="backup"
BAK_HOST=192.168.1.104
BAK_DB=mysql
TAR_DATE=`date +'%Y-%m-%d'`
TAR_DAYS=10
BAK_LOG="$BAK_DIR/$BAK_DB.backup.log"
#function to mail message
function mail_msg()
{
if [ $? -eq 0 ];then
# mail -s "$BAK_DATE Backup successful!" 510417779@qq.com
echo "$BAK_DATE Backup successful! " >>"$BAK_LOG"
else
# mail -s "$BAK_DATE Backup failed!Please check it out!!!" 510417779@qq.com
echo -e "$BAK_DATE Backup failed!Please check it out!!!" >> "$BAK_LOG"
exit 1
fi
}
#function to compress backups if $BAK_SUM==$TAR_DAYS
function compress_backups()
{
tar -zcvf "$TAR_DATE.$BAK_DB.tar.gz" $BAK_DB.*.gz
if [ $? -eq 0 ];then
mail_msg $?
rm -rf $BAK_DIR/$BAK_DB.*.gz
exit 0
else
echo "Compress Error!!!Please Check it out!!!" >> "$BAK_LOG"
exit 111
fi
}
#check dir for backups
if [ -f "$BAK_DIR/$BAK_DB.backup.log" ];then
BAK_LOG="$BAK_DIR/$BAK_DB.backup.log"
echo "$BAK_DATE: File already exsits!" >> "$BAK_LOG"
else
touch "$BAK_DIR/$BAK_DB.backup.log"
BAK_LOG="$BAK_DIR/$BAK_DB.backup.log"
echo "$BAK_DATE: File not exsits,created it." >> "$BAK_LOG"
fi
if[ "! -d $TMP_BAK_DIR" -o "! -d $BAK_DIR" ];then
mkdir $TMP_BAK_DIR
mkdir $BAK_DIR
echo "$TMP_BAK_DIR and $BAK_DIR does not exsits,created them!" >> "$BAK_LOG"
fi
# backup
mysqldump -h$BAK_HOST -u$BAK_USER -p$BAK_PASSWD --opt -R $BAK_DB|gzip -9>"$TMP_BAK_DIR/$BAK_DB.$BAK_DATE.gz"
mail_msg $?
mv "$TMP_BAK_DIR/$BAK_DB.$BAK_DATE.gz" "$BAK_DIR"
# tarball backups every ten days
cd $BAK_DIR
BAK_SUM=`ls $BAK_DIR/$BAK_DB.*.gz | wc -l`
if [ $BAK_SUM -eq $TAR_DAYS ];then
compress_backups
else
echo "Backups not enough!">/dev/null
exit 2
fi