Skip to content

Instantly share code, notes, and snippets.

@ljonesfl
Last active January 22, 2019 22:42
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 ljonesfl/1c7db1b52f1c2852c29fdd19479c4a84 to your computer and use it in GitHub Desktop.
Save ljonesfl/1c7db1b52f1c2852c29fdd19479c4a84 to your computer and use it in GitHub Desktop.
Script to create a rolling mysql backup.
#!/bin/bash
#
# This script exports the specified mysql database and deletes
# any backups older than a specified number of days.
#
# Created by Lee Jones
# http://leejon.es
#
# The folder in which to store the backups.
TARGET_DIR=
# The maximum number of days to keep a backup.
EXPIRE_DAYS=90
# The database and credentials.
DB_NAME=
DB_USER=
DB_PASS=
# Check if the target directory exists..
if [ ! -d "$TARGET_DIR" ]; then
echo "Error: Could not find $TARGET_DIR"
exit 1
fi
# Delete old backups..
echo -n "Deleting old backups.."
find $TARGET_DIR/* -mtime +$EXPIRE_DAYS -delete
echo "Done."
# Dump the current database..
BACKUP_FILE="$TARGET_DIR/backup.$(date +%F_%R)"
echo -n "Backing up to $BACKUP_FILE.."
mysqldump -u $DB_USER -p"$DB_PASS" $DB_NAME | gzip > "$TARGET_DIR/backup.$(date +%F_%R).sql.gz"
echo "Done."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment