Skip to main content

A script I run daily (via cron) for backing up MySQL databases.

#!/bin/bash

##
# MySQL Info
##
MYSQL_USER="usrname"
MYSQL_PASS="pass"
MYSQL_HOST="localhost"
MYSQL_DATABASE="mydbname"

BACKUP_DIR_ROOT="$HOME/bkup"
SQL_BACKUP_FILE="$MYSQL_DATABASE.sql"
TODAY=`date +"%m-%d-%Y"`

function zip_file () {
  zip -9 "$1" "$2" &>/dev/null
  echo "---> Zipped file $2 to $1."
}

function make_dir () {
  if [[ ! -d "$1" ]]; then
    mkdir -p "$1"
    echo "---> Created directory: $1."
  fi
}

function delete_dir () {
  if [[ -d "$1" ]]; then
    rm -rf "$1"
    echo "---> Deleted directory: $1."
  fi
}

function delete_file () {
  if [[ -f "$1" ]]; then
    rm -f "$1"
    echo "---> Deleted file: $1."
  fi
}

##
# BEGIN MAIN
##

make_dir "$BACKUP_DIR_ROOT/$MYSQL_DATABASE"
cd       "$BACKUP_DIR_ROOT/$MYSQL_DATABASE"

echo "---> Exporting MySQL databse $MYSQL_DATABASE to $SQL_BACKUP_FILE..."
mysqldump --add-drop-table -h $MYSQL_HOST -u $MYSQL_USER -p$MYSQL_PASS $MYSQL_DATABASE > $SQL_BACKUP_FILE

zip_file "$TODAY.zip" "$SQL_BACKUP_FILE"
delete_file "$SQL_BACKUP_FILE"

echo "---> Removing archived backups older than 30-days...";
find "$BACKUP_DIR_ROOT/$MYSQL_DATABASE" -type f -mtime +30 -exec rm -rf '{}' \;

echo "---> Finished!"