MySQL: backup databases in separate files and zip it to STDOUT

It’s not very comfortable to restore one database, if you have just one big fat backup file, which contains all databases.

My solution is the bash script above does the following steps:

  1. It crreates one dump file for each database.
  2. It packs all dump files in one zipfile
  3. and sends it to STDOUT.

Step 3 is very helpful e.g. for using this script with backup software like rsnapshot.

## Dumps every database to a single file, all dump files will be zipped and redirected to the stdout.
## Usage: backup-db.sh > databases.zip
##
#! /bin/bash
set -o nounset
set -o errexit

trap 'rm -rf "$BACKUP_DIR"' EXIT
BACKUP_DIR=$(mktemp -d)
MYSQL=/usr/bin/mysql
MYSQLDUMP=/usr/bin/mysqldump

databases=`$MYSQL --defaults-extra-file=/etc/mysql/credentials.cnf --default-character-set=utf8mb4 -e "SHOW DATABASES;" \
        | grep -Ev "(Database|information_schema|performance_schema)"`
for db in $databases; do
  $MYSQLDUMP --defaults-extra-file=/etc/mysql/credentials.cnf --default-character-set=utf8mb4 --force --opt --databases $db \
        > "$BACKUP_DIR/$db.sql"
done
zip -rjq - "$BACKUP_DIR"
exit 0

The corresponding gist at github: https://gist.github.com/th-schwarz/38dd9fa1cdba05506f642a633095bad7

, ,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: