Backup MySQL Database Daily and Keep for 7 days

Here is a script I quickly wrote to mysqldump a single database and keep 7 days worth of backups.

#!/bin/bash
# Script – mysqlbackup.sh
# Created by Jordansphere – 20/Jun/13

DATADIR=”/home/mysqlbackups”
USERNAME=username
PASSWORD=password
NOW=$(date +”%d-%m-%Y”)

#BACKUP DATABASE in date format (eg “MyDatabase-20-6-2013.sql”)
/usr/bin/mysqldump -u $USERNAME -p$PASSWORD –databases MyDatabase > /home/mysqlbackups/MyDatabase.$NOW.sql

# REMOVE BACKUPS MORE THAN 1 WEEK OLD – This removes all files in the directory older than a week, so be careful!!
find /home/mysqlbackups/* -mtime +7 -exec rm {} \;

 

Im sure there are other ways to skin this but I only wrote it in under 5 minutes.

Now all we have to do is put the script in the crontab:

0 2 * * * root /data/bin/mysqlbackup.sh