Skip to content

Instantly share code, notes, and snippets.

@isyutaro
Last active December 27, 2017 20:33
Show Gist options
  • Save isyutaro/9899008 to your computer and use it in GitHub Desktop.
Save isyutaro/9899008 to your computer and use it in GitHub Desktop.
backup all mysql databases as separate files
#!bash
#!/bin/bash
#
# Script to backup all mysql databases as separate files
#
# $BACKUP_PATH/<date>/<db_name>-<date>.gz
# set env variables for this script
DATESTAMP=$(date +%Y-%m-%d)
USER="backup"
PASSWORD="123456789"
BACKUP_PATH="/tmp/backup"
MAX_DAYS=60 # ~2 months
# Ignore these databases (space separated)
IGNORE="test information_schema mysql performance_schema"
# check if destination exist
if [ ! -d "$DIRECTORY/$DATESTAMP" ]; then
mkdir -p $BACKUP_PATH/$DATESTAMP
fi
# check if datestamp directory exist
# get a list of databases
databases=$(mysql --user=$USER --password=$PASSWORD -Bse 'show databases')
# dump each database in turn and compress it
for db in $databases; do
if [[ "$IGNORE" =~ "$db" ]] ; then
echo "Skipping: [$db]"
continue
fi
echo "Dumping database: [$db]"
mysqldump --user=$USER --password=$PASSWORD --databases $db > "$BACKUP_PATH/$DATESTAMP/$db-$DATESTAMP.sql"
gzip -f "$BACKUP_PATH/$DATESTAMP/$db-$DATESTAMP.sql"
done
# delete old files
find $BACKUP_PATH -maxdepth 1 -mtime +$MAX_DAYS -exec rm -rf {} \;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment