Nuffnang

Friday, January 4, 2013

MySQL Backup Script under Linux


#!/bin/bash

# The path the backups will be dumped to
DUMP_DIR="/home/backups/mysql/"

# SQL user who can access the db
SQL_USER="SQL_USERNAME"

# SQL password for above user
SQL_PASS="SQL_PASSWORD"

# SQL host
SQL_HOST="localhost"

# SQL database
SQL_DB="DATABASE_NAME"

# Back up folder name (mmddyyyy)
BACKUP_DIR="`date +%m%d%Y`"

# SQL dump file name
DUMP_FILE="`date +%m_%d_%Y_%H_%M_%S`_example.com"

# SL container name
CONTAINER="mysql_backups"

# Create backup dir if doesn't exist
if [ ! -d $DUMP_DIR$BACKUP_DIR ]; then
        mkdir -p $DUMP_DIR$BACKUP_DIR
fi

# Dump the database to /tmp/...
mysqldump -u $SQL_USER -p$SQL_PASS --host=$SQL_HOST $SQL_DB > /tmp/$DUMP_FILE.sql

tar -zcvpf $DUMP_DIR$BACKUP_DIR/$DUMP_FILE.sql.gz /tmp/$DUMP_FILE.sql

# No reason to keep the dump file
rm -rf /tmp/$DUMP_FILE.sql

# Make sure the archive exists
if [ -f $DUMP_DIR$BACKUP_DIR/$DUMP_FILE.sql.gz ]; then
        /root/slbackup.py -s $DUMP_DIR$BACKUP_DIR/ -o "$CONTAINER"

        # Remove the backup stored locally
        rm -rf $DUMP_DIR$BACKUP_DIR

        # Success
        exit 0
else
        echo "$DUMP_DIR$BACKUP_DIR/$DUMP_FILE.sq.gz does not exist."
        exit 1
fi

No comments:

Post a Comment