Skip to content

Instantly share code, notes, and snippets.

@koutoftimer
Last active October 7, 2016 11:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save koutoftimer/b14608d5b7b369b68b082c512811ddf1 to your computer and use it in GitHub Desktop.
Save koutoftimer/b14608d5b7b369b68b082c512811ddf1 to your computer and use it in GitHub Desktop.
Template for contab job about dumping mysql database for django applications
#!/usr/bin/env bash
# -*- encoding: utf-8 -*-
# Script makes a backup of mysql database by retieving settings from .env file.
#
# 'stdout' stream can be logged but script itself has no logging logic.
#
# If everything goes right, exit code will be equal to zero so you can use this
# for builing wrappers around it to infrom that backup failed execution.
# Write help string if there is not enough parameters
if [[ $1 == '-h' || $1 == '--help' || $# -ne 3 ]]
then
echo "Usage: $(basename $0) <project_dir> <project_name> <dump_dir>"
exit 1
fi
echo "[$(date -I)] dumping db"
PROJECT_ROOT=$1
PROJECT_NAME=$2
DUMP_ROOT=$3
DOT_ENV="$PROJECT_ROOT/$PROJECT_NAME/.env"
# Create directory for dump files
if $( mkdir -p $DUMP_ROOT 2>/dev/null )
then
echo "[+] '$DUMP_ROOT' exists"
else
echo "[-] '$DUMP_ROOT' cannot be created"
exit 1
fi
# Ensure in existance of file with db connection settings
if [ -f $DOT_ENV ]
then
echo "[+] '.env' exists"
else
echo "[-] '.env' exists"
exit 1
fi
# Extract database connection infromation from '.env' file
DB_NAME=$( awk -F '=' '/DB_NAME/ {print $2}' $DOT_ENV | sed -e "s/'//g" )
DB_USER=$( awk -F '=' '/DB_USER/ {print $2}' $DOT_ENV | sed -e "s/'//g" )
DB_HOST=$( awk -F '=' '/DB_HOST/ {print $2}' $DOT_ENV | sed -e "s/'//g" )
DB_PASSWORD=$( awk -F '=' '/DB_PASSWORD/ {print $2}' $DOT_ENV | sed -e "s/'//g" )
# Make database dump
DUMP_SQL_NAME="dump-$(date -I).sql"
DUMP_SQL_PATH="$DUMP_ROOT/$DUMP_SQL_NAME"
mysqldump -u $DB_USER -p$DB_PASSWORD -h $DB_HOST $DB_NAME > $DUMP_SQL_PATH 2>/dev/null
if [[ $? -eq 0 ]]
then
echo "[+] '$DUMP_SQL_PATH' created"
else
echo "[-] 'mysqldump' failed"
exit 1
fi
# Create sha1 sum for backup
DUMP_SQL_SHA_PATH="$DUMP_SQL_PATH.sha1"
sha1sum $DUMP_SQL_PATH > $DUMP_SQL_SHA_PATH 2>/dev/null
if [[ $? -eq 0 ]]
then
echo "[+] sha1 sum created"
else
echo "[-] sha1 sum was not created"
exit 1
fi
# Archive backup with a sha1 sum for it
DUMP_SQL_TAR_GZ_PATH="$DUMP_SQL_PATH.tar.gz"
cd $DUMP_ROOT
tar -czvf "$DUMP_SQL_NAME.tar.gz" "$DUMP_SQL_NAME" "$DUMP_SQL_NAME.sha1" &>/dev/null
if [[ $? -eq 0 ]]
then
echo "[+] archive created"
# Clean up temporary and stale fils
rm $DUMP_SQL_PATH $DUMP_SQL_SHA_PATH && find $DUMP_ROOT -mtime +6 -delete
else
echo "[-] archiving failed"
exit 1
fi
# Return status code of clean up step
exit $?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment