Created
May 23, 2014 16:49
-
-
Save dennisfrank/b7a27303e15711d86c25 to your computer and use it in GitHub Desktop.
Shell script to import a remote database into local environment
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
#!/bin/sh | |
# Import a remote database into a local database | |
# ---------------------------------------------- | |
# | |
# Based on http://danherd.net/quick-script-synchronise-from-a-remote-expressionengine-database/ | |
# | |
# Don’t forget chmod +x to make the script executable. | |
# | |
# Change the extension to .command to run the script directly from OS X Finder. | |
# | |
# Settings | |
# -------- | |
# Set SSH host | |
SSHHOST="[email protected]" | |
# Set mysqldump client | |
MYSQLDUMP="/Applications/MAMP/Library/bin/mysqldump" | |
# Set mysql client | |
MYSQL="/Applications/MAMP/Library/bin/mysql" | |
# Set local database host | |
LOCALDBHOST="localhost" | |
# Set local database user | |
LOCALDBUSER="dbuser" | |
# Set local database name | |
LOCALDBNAME="dbname" | |
# Set local database password | |
LOCALDBPASS="dbpassword" | |
# Set directory for local database backup | |
LOCALBACKUPDIR="../../tmp/" | |
# Set remote database host | |
REMOTEDBHOST="database.example.com" | |
# Set remote database user | |
REMOTEDBUSER="dbuser" | |
# Set remote database name | |
REMOTEDBNAME="dbname" | |
# Set remote database password (leave single quotes for special characters) | |
REMOTEDBPASS="'dbpassword'" | |
# Let’s go! | |
# --------- | |
# Run script in current directory | |
cd "`dirname "$0"`" | |
# Backup local database | |
$MYSQLDUMP \ | |
-h $LOCALDBHOST \ | |
-u $LOCALDBUSER \ | |
$LOCALDBNAME \ | |
-p$LOCALDBPASS \ | |
| gzip > $LOCALBACKUPDIR/BACKUP_$(date +%Y-%m-%d_%H-%M-%S)_local_$LOCALDBNAME.sql.gz | |
# Connect to the remote machine and get a compressed dump of the database | |
ssh $SSHHOST \ | |
"cd tmp && | |
mysqldump \ | |
-h $REMOTEDBHOST \ | |
-u $REMOTEDBUSER \ | |
$REMOTEDBNAME \ | |
-p$REMOTEDBPASS \ | |
| gzip > $REMOTEDBNAME.sql.gz" | |
# Connect again and copy the compressed dump created above into the local temporary files folder | |
scp $SSHHOST:~/tmp/$REMOTEDBNAME.sql.gz /tmp/ | |
# Decompress the file | |
gunzip \ | |
-f /tmp/$REMOTEDBNAME.sql.gz | |
# Load the decompressed dump into the local database server | |
$MYSQL \ | |
-h $LOCALDBHOST \ | |
-u $LOCALDBUSER \ | |
-p$LOCALDBPASS \ | |
-D $LOCALDBNAME \ | |
< /tmp/$REMOTEDBNAME.sql | |
# Delete the file from the local temporary files folder | |
rm /tmp/$REMOTEDBNAME.sql | |
# Connect again and delete the file from the remote temporary files folder | |
ssh $SSHHOST \ | |
"rm tmp/$REMOTEDBNAME.sql.gz" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment