Ad_Feed

Wednesday, December 30, 2015

How to backup multiple Mysql databases and automatically delete

The script below was adapted from iHRIS Backups (http://wiki.ihris.org/wiki/Backups) which was designed to backup one database. The script below will backup all databases in Mysql.

There is the option to remove database backup files older than 7days except from the first day of the month.


#!/bin/sh
MHOST=localhost
MUSER=db_username
MPASS=db_password
BACKUPDIR=/db/backup/dir

MYSQL="$(which mysql)"
MYSQLDUMP="$(which mysqldump)"

SUFFIX=`date +%F`
cd $BACKUPDIR

echo "Run MySQL backup"
DBS="$($MYSQL -u $MUSER -h $MHOST -p$MPASS -Bse 'show databases')"
for db in $DBS
do
    $MYSQLDUMP -u $MUSER -h $MHOST -p$MPASS $db > backup_${db}_${SUFFIX}.sql
    bzip2 -f backup_${db}_${SUFFIX}.sql
done
## Uncomment the following line to remove backup files older than 7 days except from the first day of the month.
#find $BACKUPDIR -name "backup_*.sql.bz2" -mtime +7 -not -name "backup_*-01.sql.bz2" -exec rm {} \;


Save the file, and ensure the script is executable using the command chmod a+x newfile.