James Emmrich

22 Feb, 2010

Automatic database backup via script

Posted by: James In: Linux|ProTip|Web Development

As mentioned before somewhere in my blog, here is the script I have written to back up my databases. This is actually my local backup script, I have a much different one on the server which uses a passwordless ssh connection to backup the databases offsite.

#!/bin/sh
# Database backup 2008 <jemmrich@gmail.com>
# Nightly Usage:
# 0 0 * * * /home/james/Dropbox/Home/mobilewolf/scripts/backup.sh &> /dev/null

LOGFILE="/home/james/Dropbox/Home/mobilewolf/databases/databases.log"
BACKUPDIR="/home/james/Dropbox/Home/mobilewolf/databases"
STARTTIME="$(date +%Y-%m-%d-%r)"

# MySQL Login
SQLUSER="sqluser"
SQLPASS="sqlpass"

# Dump databases
echo "*** Database Backup Started: $STARTTIME" >> $LOGFILE

# Keep yesterdays databases
rm -f $BACKUPDIR/yesterday/*
mv $BACKUPDIR/*.gz $BACKUPDIR/yesterday/

for i in `echo "show databases" | mysql -u $SQLUSER -p$SQLPASS | grep -v Database`;
do
 mysqldump -u $SQLUSER -p$SQLPASS $i > /tmp/$i.sql
 echo $i >> $LOGFILE
 gzip /tmp/$i.sql

 # Send Databases
 cp /tmp/*.sql.gz $BACKUPDIR/

 # Remove our dumps to keep us clean
 rm -f /tmp/*.sql.gz
done

echo "*** Database Backup Ended: $(date +%Y-%m-%d-%r)" >> $LOGFILE
echo "\n" >> $LOGFILE

Setup

  1. Change the user and password to a user that has ability to access all databases for dump
  2. Download and set executable permissions chmod +x backup_databases.sh
  3. edit cron to execute every night: crontab -e
  4. add: 0 0 * * * /home/james/Dropbox/Home/mobilewolf/scripts/backup_databases.sh &> /dev/null

Ideas for your setup

  • The line following “Send databases” replace cp, with scp to send the databases to remote server. You will need to have passwordless ssh connections setup.
  • Have the log file emailed to you once completed

My Future Improvements

  • Enable backup archiving for the past week rotated daily so I can go back to a database from 2 or 3 days or even a week ago


Tweet This

No Responses to "Automatic database backup via script"

Comment Form

Categories

Upcoming Events

  • Mon, Mar 12:CMRC Pro National - The Wastlands
  • Sat, Mar 24:Supercross Toronto
  • Thu, May 10:CMRC Pro National - Whispering Pines Raceway?????
  • Sun, Jun 17:CMRC Pro National - Wild Rose MX Park
  • Sun, Jun 24:CMRC Pro National - Castrol Raceway
  • Wed, Jul 4:CMRC Pro National - Riverglade MX Park
  • Sat, Jul 14:CMRC Pro National - Gopher Dunes Raceway
  • Sun, Jul 22:CMRC Pro National - Ste Julie
  • Tue, Aug 7:CMRC Pro National - Sand Del Lee
  • Mon, Aug 13 – Sun, Aug 19:Walton TransCan