Skip to content

Instantly share code, notes, and snippets.

@cullylarson
Last active March 2, 2016 00:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cullylarson/bb7fa43f7342ab0cea97 to your computer and use it in GitHub Desktop.
Save cullylarson/bb7fa43f7342ab0cea97 to your computer and use it in GitHub Desktop.
Backup Database, with Rotation
#!/bin/bash
if [[ -z "$1" ]]; then exit 1; fi
if [[ -z "$2" ]]; then exit 1; fi
TASK=$1
# Backup folders
BK_BASE=/path/to/backup/folder
BK_DAILY=$BK_BASE/daily
BK_WEEKLY=$BK_BASE/weekly
BK_MONTHLY=$BK_BASE/monthly
# How many backups to keep
KEEP_DAILY=7
KEEP_WEEKLY=4
DBH=<database host>
DBU=<database user>
DBP=<database password>
DBN=$2
# Backup database
if [[ $TASK == "do-daily" ]]; then
mysqldump -h $DBH -u $DBU -p$DBP $DBN | gzip -> $BK_DAILY/$DBN-`date +'%Y%m%d%H%M%S'`.sql.gz
exit 0
fi
# Copy the newest daily backup to weekly, and delete all but latest KEEP_DAILY daily backups
if [[ $TASK == "do-weekly" ]]; then
cp `ls -1td $BK_DAILY/$DBN* | head -n 1` $BK_WEEKLY
ls -1trd $BK_DAILY/$DBN* | head -n -$KEEP_DAILY | xargs -d '\n' rm -f
exit 0
fi
# Copy the newest daily backup to monthly, and delete all but latest KEEP_WEEKLY weekly backups
if [[ $TASK == "do-monthly" ]]; then
cp `ls -1td $BK_DAILY/$DBN* | head -n 1` $BK_MONTHLY
ls -1trd $BK_WEEKLY/$DBN* | head -n -$KEEP_WEEKLY | xargs -d '\n' rm -f
exit 0
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment