Skip to content

Instantly share code, notes, and snippets.

@ggaona
Last active October 22, 2020 16:19
Show Gist options
  • Save ggaona/454821280a55ce82a7275a4097c91f88 to your computer and use it in GitHub Desktop.
Save ggaona/454821280a55ce82a7275a4097c91f88 to your computer and use it in GitHub Desktop.
MySQL multiple databases backup script
#!/bin/bash
# Backup multiple MySQL databases (in same host) via `mysqldump`.
# By ggaona
#
# Requirements:
#
# + mysqldump
# + MySQL password provided in '.my.cnf' file; example file:
#
# [client]
# password=your_pass
#
# This script will create a gzipped backup file, (i.e. '*.sql.gz*') for each
# specified database, with the following name:
#
# <database_name>-<yyyyMMdd>_<HHmm>.sql.gz
#
# Each file will be saved in a database specific subdirectory (created in the
# specified backup path).
#
# Example result for script execution on 2019-01-01 at 1:00am, for databases
# 'db1' and 'db2' with specified backup path '/backups':
#
# backups/
# db1/db1-20190101_0100.sql.gz
# db2/db2-20190101_0100.sql.gz
#
# Additionally, old backups (with date older than the specified backup days)
# will be removed.
#
# IMPORTANT - file permissions must be updated for this script to be able to
# execute:
#
# $ chmod +x /path/to/mysql-backup.sh
#
# To run script on a regular basis, update crontab file (`$ crontab -e`); for
# example (execute every day at 1am):
#
# 0 1 * * * /path/to/mysql-backup.sh
# CONFIGURATION START - Only edit below this line
# =============================================================================
# DB SETTINGS
MYSQL_HOST='127.0.0.1'
MYSQL_PORT='3306'
MYSQL_USER='root'
MYCNF_PATH=${HOME}
# DATABASES TO BACKUP
DATABASES=('db1' 'db2')
# BACKUP SETTINGS
BACKUP_PATH=${HOME}'/backups'
BACKUP_DAYS=10
# CONFIGURATION END - Do not edit below this line
# =============================================================================
# set backup date and time
DATETIME=`date +"%Y%m%d_%H%M"`
# create backups
for DB in "${DATABASES[@]}"
do
mkdir -p ${BACKUP_PATH}/$DB
mysqldump --defaults-extra-file=${MYCNF_PATH}/.my.cnf \
-h ${MYSQL_HOST} \
-P ${MYSQL_PORT} \
-u ${MYSQL_USER} \
--single-transaction \
--lock-tables=false \
--databases $DB | gzip > ${BACKUP_PATH}/$DB/$DB-${DATETIME}.sql.gz
done
# delete old backups
find ${BACKUP_PATH} -type f -name "*.sql.gz" -mtime +$((BACKUP_DAYS - 1)) -delete
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment