ck's archive: database backups

Database Backups (3 comments)

I didn't like the way I was maintaining database backups, so I wrote a new script. This one dumps each database in my MySQL instance every night and keeps a rolling collection of that last three nightly backups along with the last six weeklies.

#!/bin/sh

DATE=`date +%Y%m%d`;
DAYOFWEEK=`date +%u`;

# /var/lib/mysql contains one directory per database, plus lost+found
# because it's on its own ext3 filesystem.
for DB in `/usr/bin/find /var/lib/mysql/* -maxdepth 0 -type d -not -name 'lost+found' | /usr/bin/cut -d '/' -f 5`; do

# Dump a nightly file with today's date.
FILE=${DB}-${DATE};
/usr/bin/mysqldump --user=root --password=<redacted> ${DB} > /backups/db/nightly/${FILE};
/bin/bzip2 -9 /backups/db/nightly/${FILE};

# Now that the file's written, remove all but the three
# most recent versions.
/bin/ls -1 /backups/db/nightly/${DB}-* | /usr/bin/head -n '-3' | /usr/bin/xargs rm -f;

# If it's Sunday, do a weekly backup as well.
if [ ${DAYOFWEEK} = 7 ]; then

# Make a hard link to the nightly backup that was just created.
FILE=${FILE}.bz2
/bin/ln /backups/db/nightly/${FILE} /backups/db/weekly/${FILE};

# Keep most recent 6 weeks.
/bin/ls -1 /backups/db/weekly/${DB}-* | /usr/bin/head -n '-6' | /usr/bin/xargs rm -f;

fi

done

My question to you, dear Internet: how could I make this better/faster/cleaner/prettier?

search the archives:

Main archive listing

Copyright © 2001-2012 Chris Kuehn