Skip to content

Instantly share code, notes, and snippets.

@kevinsmith
Created November 18, 2014 22:51
Show Gist options
  • Save kevinsmith/027cc717a2917b5d2cd2 to your computer and use it in GitHub Desktop.
Save kevinsmith/027cc717a2917b5d2cd2 to your computer and use it in GitHub Desktop.
Script to sync staging (sandbox) DB and file uploads with local environment
#!/bin/sh
#
# sandsync.sh
#
# This is a shell script for keeping sandbox and local EE
# environments in sync. It takes a backup of a project's sandbox database,
# clears the local database and imports the remote's backup into local,
# and performs a one-way sync of the uploads directory from remote to local.
# Drop it in the directory above your version-controlled projected directory.
# Syncing of the uploads folder does require public key authentication with the
# sandbox server.
#
# It takes 1 required argument: the database password.
#
# Usage: $ ./sandsync.sh Db_Pass
#
#
# EDIT THESE ON A PER-PROJECT BASIS
REMOTE_HOST="123.123.2.4"
PROJECT="project_name"
BACKUP_PATH="DB Backups/"
UPLOADS_PATH="/Users/username/Sites/$PROJECT/site/public_html/uploads/"
LOCAL_DB_USER="local_dbuser"
LOCAL_DB_NAME="local_db_"$PROJECT
REMOTE_DB_USER="sandbox_dbuser"
REMOTE_DB_NAME="sandbox_db_"$PROJECT
REMOTE_SSH_PORT="22"
REMOTE_SSH_USER="remote_user"
# ONLY EDIT BELOW THIS LINE IF YOU KNOW WHAT YOU'RE DOING
DB_PASS=$1
DATE=$(date +"%Y-%m-%d")
BACKUP_FILENAME=$REMOTE_DB_NAME"-"$DATE".sql.gz"
echo "Backing up sandbox database to $BACKUP_PATH$BACKUP_FILENAME..."
mysqldump -u $REMOTE_DB_USER -p$DB_PASS -h$REMOTE_HOST $REMOTE_DB_NAME --add-drop-table | gzip -9 > $BACKUP_PATH$BACKUP_FILENAME
echo ""
echo "Clearing local database..."
mysqldump -u $LOCAL_DB_USER -p$DB_PASS --add-drop-table --no-data $LOCAL_DB_NAME | grep ^DROP | mysql -u $LOCAL_DB_USER -p$DB_PASS $LOCAL_DB_NAME
echo ""
echo "Loading remote backup into local database..."
gunzip < $BACKUP_PATH$BACKUP_FILENAME | mysql -u $LOCAL_DB_USER -p$DB_PASS $LOCAL_DB_NAME
# This requires public key authentication with the sandbox
echo ""
echo "Syncing sandbox's uploads folder..."
rsync -azP --delete -e 'ssh -p $REMOTE_SSH_PORT' $REMOTE_SSH_USER@$REMOTE_HOST:/home/$PROJECT/public_html/uploads/ $UPLOADS_PATH
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment