Created
June 11, 2019 14:05
-
-
Save gadelkareem/24f8ad51667f4488ff7508a7b72d38a2 to your computer and use it in GitHub Desktop.
MySQL backup restore script https://gadelkareem.com/2019/06/11/database-backup-restore-via-s3/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
set -euo pipefail | |
cd `dirname $0` | |
# lock it | |
PIDFILE="/tmp/$(basename "${BASH_SOURCE[0]%.*}.pid")" | |
exec 200>${PIDFILE} | |
flock -n 200 || ( echo "${BASH_SOURCE[0]} script is already running. Aborting . ." && exit 1 ) | |
PID=$$ | |
echo ${PID} 1>&200 | |
TIMESTAMP=$(date '+%Y_%m_%d__%H_%M_%S') | |
mkdir -p /var/backups/databases | |
cd /var/backups/databases | |
function backup(){ | |
DB=${1} | |
FILENAME=${TIMESTAMP}.sql.bz2 | |
ROUTE="${DB}/${ENV}" | |
DIR=/var/backups/databases/${ROUTE} | |
FILE="${DIR}/${FILENAME}" | |
mkdir -p "${DIR}" | |
cd "${DIR}" | |
echo Backing up ${DB} | |
mysqldump -uroot --skip-lock-tables --single-transaction --add-drop-table ${DB} | bzip2 > ${FILE} | |
echo Uploading ${DB} | |
/usr/bin/s3cmd put ${FILE} s3://backups/db/${ROUTE}/${FILENAME} | |
rm -f ${FILE} | |
echo ${FILENAME} > latest | |
/usr/bin/s3cmd put latest "s3://backups/db/${ROUTE}/latest" | |
rm -f latest | |
} | |
function restore(){ | |
DB=${1} | |
ROUTE="${DB}/${ENV}" | |
DIR=/var/backups/databases/${ROUTE} | |
mkdir -p "${DIR}" | |
cd "${DIR}" | |
/usr/bin/s3cmd get --force s3://backups/db/${ROUTE}/latest | |
/usr/bin/s3cmd get --force s3://backups/db/${ROUTE}/$(cat latest) - > latest.sql.bz2 | |
bzcat latest.sql.bz2 | mysql -uroot ${DB} | |
rm -f latest | |
rm -f latest.sql.bz2 | |
} | |
for i in "${@:2}" | |
do | |
$1 $i | |
done | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment