Shell Script to Backup and Rotate Mysql Database

#!/bin/bash
#Author : Amit K Nepal
#Last Modified : Nov 01 2011
BACKUP_DIR=/db_backups
DB_NAME=dbname
TSTAMP=`date +%Y%m%d`
FILENAME=$BACKUP_DIR/$DB_NAME.gz
Notify=1
Rotate=8
logfile=$BACKUP_DIR/backup.log
echo ".............Backup Script Running on $TSTAMP............" >> $logfile
let i=$Rotate-1
if [ -f "$FILENAME.$Rotate" ];then
echo "$FILENAME.$Rotate Found,Deleting" >> $logfile
rm -rf $FILENAME.$Rotate
else
echo "$FILENAME.$Rotate Not Found, Not Removing" >> $logfile
fi
while [ $i -ge 1 ]
do
let j=$i+1;
if [ -f "$FILENAME.$i" ];then
echo $FILENAME.$i exists and is being moved to $FILENAME.$j >> $logfile
mv $FILENAME.$i $FILENAME.$j
else
echo $FILENAME.$i not found, not moving to $FILENAME.$j >> $logfile
fi
let i=$i-1
done
mysqldump --database $DB_NAME | gzip > $FILENAME.1
echo "..........Backup Script Completed,Exiting Now.$TSTAMP........." >> $logfile
if [ $Notify == 1 ];then
SUBJECT="Database Backup Completed on:`hostname`"
ADMIN="admin email"
function message {
echo -e "Hi there,\n"
echo -e "..........................................................\n"
echo -e "This is to notify that database backup has completed on:`hostname`\n"
echo -e "Date-Time:`date`\n"
echo -e "--------------------------------------------------------\n"
}
message|mail -s "$SUBJECT" "$ADMIN"
fi

Script to move the latest dump to a remote server (Run it may be once a month )


#!/bin/bash
#Author : Amit K Nepal
#Last Modified : Nov 02 2011
REMOTE_SRV=server ip or hostname
BACKUP_DIR=/db_backups
TSTAMP=`date +%Y%m%d`
FILENAME=$BACKUP_DIR/dump.gz.1
Notify=1
KEY=path to key file
ADMIN="adminemail"

logfile=$BACKUP_DIR/rsync.log
echo ".............Moving to Remote Server at $TSTAMP............" >> $logfile

if [ -f "$FILENAME" ];then
echo "$FILENAME Found,Syncing Now" >> $logfile
rsync --bwlimit=1024 -Pzarve "ssh -p 6212 -i $KEY" $FILENAME $REMOTE_SRV:/$BACKUP_DIR/
else
echo "$FILENAME Not Found, Not Removing" >> $logfileo
echo "Db Backup Not Found to sync" | mail -s "Db Backup Not Found" $ADMIN
fi
echo "..........Backup Script Completed,Exiting Now.$TSTAMP........." >> $logfile
if [ $Notify == 1 ];then
SUBJECT="Database Backup Completed on:`hostname`"
function message {
echo -e "Hi there,\n"
echo -e "..........................................................\n"
echo -e "This is to notify that database backup has completed on:`hostname`\n"
echo -e "Date-Time:`date`\n"
echo -e "--------------------------------------------------------\n"
}
message|mail -s "$SUBJECT" "$ADMIN"
fi