#!/bin/sh
#MySQL backup script
### System Setup ###
KEEPDAYS=7
BACKUPPREFIX=backup
BACKUPPATH="/backups/mysql"
OWNER=sysadmin
### MySQL Setup ###
MUSER="root"
MPASS="#PASSWORD#"
MHOST="localhost"
MYSQL="$(/usr/bin/which mysql)"
MYSQLDUMP="$(/usr/bin/which mysqldump)"
GZIP="$(/usr/bin/which gzip)"
GREP="$(/usr/bin/which grep)"
CUT="$(/usr/bin/which cut)"
RM="$(/usr/bin/which rm)"
DATE="$(/usr/bin/which date)"
CHOWN="$(/usr/bin/which chown)"
FIND="$(/usr/bin/which find)"
MYSQLADMIN="$(/usr/bin/which mysqladmin)"
# sanity checks
regnumcheck='^[0-9]+$'
if [[ ! $KEEPDAYS =~ $regnumcheck ]] ; then
echo please enter a valid numeric number to keep the amount of backups
exit 2
fi
if [[ ! -d $BACKUPPATH ]]; then
echo unable to find the folder : $BACKUPPATH for var scriptpath
exit 2
fi
echo starting cleanup
### Cleanup old backups ###
LSOUTPUT="$($FIND $BACKUPPATH -maxdepth 1 -type d -ctime +$KEEPDAYS -iname 'backup.*' -printf '%f\n' | sort)"
for results in $LSOUTPUT
do
if [[ ! "x$results" == "x" ]];
then
echo "$BACKUPPATH/$results"
if [[ ! -d $BACKUPPATH/$results ]] ; then
echo error the folder $BACKUPPATH/$results you are parsing should exist.. what are you doing?
exit 2
else
echo deleting $BACKUPPATH/$results, its older then $KEEPDAYS days
$RM -r $BACKUPPATH/$results
if [[ -d $BACKUPPATH/$results ]] ; then
echo error, i was unable to delete $BACKUPPATH/$results
exit 2
fi
fi
fi
done
echo starting backup
### Start Backup ###
BACKUP=$BACKUPPATH/$BACKUPPREFIX.$(date +"%Y%m%d.%H%M.%S")
[ ! -d $BACKUP ] && mkdir -p $BACKUP || :
if [[ ! -d $BACKUP ]] ; then
echo error, i was unable to create $BACKUP
exit 2
fi
$MYSQLADMIN -u $MUSER -h $MHOST -p$MPASS stop-slave
### Start MySQL Backup ###
# Get all databases name
DBS="$($MYSQL -u $MUSER -h $MHOST -p$MPASS -Bse 'show databases')"
for db in $DBS
do
echo $db
FILE=$BACKUP/mysql-$db.$(date +"%Y%m%d%.%H%M.%S").gz
$MYSQLDUMP -u $MUSER -h $MHOST -p$MPASS $db | $GZIP -9 > $FILE
done
$MYSQLADMIN -u $MUSER -h $MHOST -p$MPASS start-slave
$CHOWN -R $OWNER:$OWNER $BACKUP