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
- Change the user and password to a user that has ability to access all databases for dump
- Download and set executable permissions chmod +x backup_databases.sh
- edit cron to execute every night: crontab -e
- 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















Recent Comments