Wednesday, November 29, 2006

Cron and MySql Database Backups

This is nothing very special or exciting, it's just a script that I run as a cron job to make the backup of a mysql database. It can be customized according to several parameters. The script is intended to be run once a day, in fact the file name that is created contains the date in the shape of month_day_year. If you need to run this script more than once per day, you need to add also the time in the file name (otherwise the previous backup in the same day gets overwritten).

You can also customize the parameters that you pass to the programs, e.g., mysqldump and gzip. And of course, you need to set the right values for the username, the password and the database name (and also the path where the backup will be save, which, by default it's the backup directory in your home directory, so please make sure this directory exists).

Here's the script, hoping you find it useful somehow :-)

#!/bin/sh

DATABASE=bibliography
USER=root
PASSWORD=pippo
FILENAME=backup_
PATH=$HOME/backup
MYSQLDUMP=/usr/bin/mysqldump
GZIP="/bin/gzip --best"

BACKUP=$PATH/$FILENAME`/bin/date +%m_%d_%y`.sql.gz

if $MYSQLDUMP -u $USER -p$PASSWORD $DATABASE | $GZIP > $BACKUP; then
echo "backup successful: $BACKUP";
true;
else
echo "errors during backup";
false;
fi

No comments: