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