Mysql Backup Script

 

Backing up your databases is critical so I have written a script to do such. This script is designed to be launched as a cronjob, but you can launch it from command line just as easily.

#!/bin/bash

# 0 3 * * * /home/_USER_/bin/mysql_backup.sh > /dev/null 2>&1

STAMP=`date +"%F"`;
EPOCH=`date +"%s"`;
USER=_USER_
TMPBKDIR=/home/$USER/sqlBackup/.tmp/
BKDIR=/home/$USER/sqlBackup/
DBNAME=database_name
DBUSER=database_user
DBPASS=database_pass

TBKNAME=${TMPBKDIR}${DBNAME}-${STAMP}_${EPOCH}.sql
ABKNAME=${BKDIR}${DBNAME}-${STAMP}_${EPOCH}.sql

[ -d $BKDIR ] || mkdir $BKDIR
[ -d $TMPBKDIR ] || mkdir $TMPBKDIR
[ -f $BKNAME ] || rm -rf $TBKNAME
[ -f $ABKNAME ] || rm -rf $ABKNAME

mysqldump -u${DBUSER} -p${DBPASS} ${DBNAME} > ${TBKNAME}
mv $TBKNAME $ABKNAME && gzip $ABKNAME

The script will create a primary directory to hold the backups, and inside this directory it will create a .tmp directory to be used during the dump process. There is no way a backup will have the same name since the EPOCH time stamp is being used; therefore, it is safe to just rm the file if it exists.

 

Illusion is the first of all pleasures.
-- Oscar Wilde