Difference between revisions of "MySQL Backup Script"

From wikidb
Jump to: navigation, search
(Created page with "<tt> <pre> #!/bin/bash # Number of days to keep backups DAYS=7 # List of databases to back up DBS=(crowlivia wikidb gallery) # Who to email when it fails EMAIL=epp@zdome.net E...")
 
 
Line 43: Line 43:
 
done
 
done
  
</pre.
+
</pre>
 
</tt>
 
</tt>

Latest revision as of 14:14, 30 November 2014

#!/bin/bash
# Number of days to keep backups
DAYS=7
# List of databases to back up
DBS=(crowlivia wikidb gallery)
# Who to email when it fails
EMAIL=epp@zdome.net
EMAILFROM=noreply@localhost

# Perform the backup...
DATE=$(date -u '+%Y%m%dT%H%M')
BACKUPDIR=~/dbbackup/dbbackups/
TEMP=$BACKUPDIR/tmp.sql.gz
for DB in ${DBS[@]}
do
    DBDIR=$BACKUPDIR/$DB
    if [[ ! -d $DBDIR ]]
    then
	mkdir $DBDIR
    fi
    # You'll notice that the password is not specified here.
    # The password for the MySQL root account is specified
    # in ~/.my.cnf.
    # This way, it won't show up when other users run "ps".
    mysqldump -u root $DB | gzip > $TEMP
    if [[ "$?" -ne 0 ]]
    then
	echo "Backup of database $DB failed."
	mailx -s "MySQL backup failure" "$EMAIL" -S from="$EMAILFROM" <<EOF
MySQL backup failed.
Database: $DB
Time: $DATE (UTC)
EOF
	rm $TEMP
    else
	# Delete old backups, but only if we succeeded at creating
	# a new one.
	find $DBDIR -mtime +$DAYS -delete
	mv $TEMP $DBDIR/$DB-$DATE.sql.gz
    fi
done