MySQL all databases backup in separate files

From DevOps Notebook
Revision as of 22:33, 8 January 2022 by MilosZ (talk | contribs)
#! /bin/bash

# crontab every 15 minutes
# */5 * * * * /path/to/backup.sh 2>&1

TIMESTAMP=$(date +"%F")
BACKUP_DIR="/backup/mysql/$TIMESTAMP" # mkdir -p /backup/mysql if you don't have it
MYSQL_USER="root" # user with backup privileges
MYSQL_PASSWORD="yourpassword" 
MYSQL=/usr/bin/mysql
MYSQLDUMP=/usr/bin/mysqldump

mkdir -p "$BACKUP_DIR/mysql"

databases=`$MYSQL --user=$MYSQL_USER -p$MYSQL_PASSWORD -e "SHOW DATABASES;" | grep -Ev "(Database|information_schema|performance_schema)"`

for db in $databases; do
  $MYSQLDUMP --force --opt --user=$MYSQL_USER -p$MYSQL_PASSWORD --databases $db | gzip > "$BACKUP_DIR/mysql/$db.gz"
done