andybeak
12/16/2015 - 12:29 PM

Backup all databases on a host

Backup all databases on a host

#!/bin/bash

# outputs all databases in the live database to gzipped sql dumps
# removes all the dumps that are older than 8 hours
# restore the dump with gunzip < outputfile.sql.gz | mysql < mysql options>

USER="myuser"
PASSWORD="password"
HOST="database.server"
OUTPUT="/home/ubuntu/database_backups/backups"

databases=`mysql -h $HOST -u $USER -p$PASSWORD -e "SHOW DATABASES;" | tr -d "| " | grep -v Database`

for db in $databases; do
    if [[ "$db" != "information_schema" ]] && [[ "$db" != "performance_schema" ]] && [[ "$db" != "mysql" ]] && [[ "$db" != _* ]] ; then
        echo "Dumping database: $db"
        mysqldump -h $HOST -u $USER -p$PASSWORD --databases $db | gzip > $OUTPUT/`date +%Y%m%d%T`.$db.sql.gz
    fi
done

find $OUTPUT/*.sql.gz -mmin +480 -exec rm {} \;