You are here:
> Bash scripts
> Backing up MySQL databases (snapshot)
> Bash scripts
> Backing up MySQL databases (snapshot)
There are fixed settings that I use to backup my MySQL databases. There are quite a few that need to be backed up, so I wrote the following script:
#!/bin/sh
DATE=`date '+%Y_%m_%d-%H-%M-%S'`; # date to use in filename
WORKING_DIR=`dirname $0`;
doBackup ()
{
for ARG in "$@"
do
echo "Backing up "$ARG;
#if the file has not changed since the last time a snapshot was taken, do not create another file..
if [ ! -d $WORKING_DIR"/mysqlDump/$ARG/" ]
then
mkdir $WORKING_DIR"/mysqlDump/$ARG/";
fi
MOST_RECENT_FILE=$WORKING_DIR"/mysqlDump/$ARG/"`ls -t $WORKING_DIR"/mysqlDump/$ARG" | head -n 1`;
mysqldump --add-drop-table --routines --user=rdy --password=lamepass --skip-dump-date $ARG > $WORKING_DIR"/mysqlDump/$ARG/$ARG""_"$DATE".sql";
if [ ! -d $MOST_RECENT_FILE ]
then
STRING=`cmp $WORKING_DIR"/mysqlDump/$ARG/$ARG""_"$DATE".sql" $MOST_RECENT_FILE`;
if [ -z "$STRING" ]
then
rm $WORKING_DIR"/mysqlDump/$ARG/$ARG""_"$DATE".sql";
fi
fi
done
}
doBackup "rdyweb" "Clicker" "apartment"
sleep 3;
It's really pretty simple - it does the following:
- find out what the working directory is (where the script is executed from) and uses that as the path to work with
- checks to see if a folder exists for the database - if it doesn't, will create one
- find out what the most recently modified file in the folder for the database in question is
- dump the database (this is for comparison)
- compare the most recent one to the one that has just been created - if they match then remove the one that has just been created
- done