Skip to content

Instantly share code, notes, and snippets.

@olragon
Created April 12, 2015 05:34
Show Gist options
  • Save olragon/0a5e67e030725ab6d78a to your computer and use it in GitHub Desktop.
Save olragon/0a5e67e030725ab6d78a to your computer and use it in GitHub Desktop.
Backup MySQL databases, backup files split by date-time and database name
# file: /root/.my.cnf
[client]
user = MYSQL_USER
password = MYSQL_PASSWORD
host = MYSQL_HOST
#!/usr/bin/env bash
# file: /root/scripts/backup-db.sh
DB_BACKUP_DIR_ROOT="/data/backup/mysql"
DB_BACKUP_DIR_TODAY="$DB_BACKUP_DIR_ROOT/`date +%Y-%m-%d`"
HN=`hostname | awk -F. '{print $1}'`
# Create the backup directory
mkdir -p $DB_BACKUP_DIR_TODAY
# Remove backups older than 1 day
find $DB_BACKUP_DIR_ROOT/ -maxdepth 1 -type d -mtime +1 -exec rm -rf {} \;
# Backup each db in the server, skip schema dbs though
for db in $(mysql -Bse 'show databases'|egrep -vi 'information_schema|performance_schema');
do mysqldump --max-allowed-packet=1024M -B $db | gzip > "$DB_BACKUP_DIR_TODAY/$HN-$db-$(date +%Y-%m-%dT%H:%M:%S).sql.gz";
done
# Backup everyday at 0:0:0 and email output to YOUR@EMAIL.HERE
# crontab -e
MAILTO="YOUR@EMAIL.HERE"
0 0 * * * /root/scripts/backup-db.sh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment