#!/bin/bash
# base directory for mysql backups
BASEDIR=/home/backup/mysql
# today date in format YYYY-MM-DD
DATE=`date +%Y-%m-%d`
# database list (without `mysql` and `information_schema` databases)
DATABASES=`echo "SHOW DATABASES" | mysql | sed 1d | grep -v ^mysql$ | grep -v ^information_schema$`
# destination directory
DSTDIR=$BASEDIR/$DATE
# if not force
if [ "$1" != "-f" ]; then
# if DSTDIR already exists
if [ -e $DSTDIR ]; then
echo "Today backup already exists, use -f to override"
exit 0
fi
fi
# create DSTDIR (if doesn't exist)
mkdir -p $DSTDIR
# dump all the databases
for DATABASE in $DATABASES; do
echo -n "Dumping database $DATABASE... "
(
mysqldump --single-transaction -R $DATABASE > $DSTDIR/$DATABASE.sql
) && (
echo -n "dumped, gzipping... "
(
gzip -f $DSTDIR/$DATABASE.sql
) && (
echo "ok"
) || (
echo "error gzipping file $DSTDIR/$DATABASE.sql"
)
) || (
echo "error dumping database $DATABASE"
)
done
# finished
echo "All databases have been backed up"