Skip to content

Instantly share code, notes, and snippets.

@cmbirk
Last active December 10, 2015 23:08
Show Gist options
  • Save cmbirk/4507155 to your computer and use it in GitHub Desktop.
Save cmbirk/4507155 to your computer and use it in GitHub Desktop.
Bash command to help sync local db with remote server
#!/bin/bash -x
usage()
{
cat << EOF
usage: $0 options
OPTIONS:
-h Show this message
-f Filename to save db dump as
(optional, only downloads dump, does not sync)
-c SSH connection string
-u External database user
-p External database password
-n External database name
-U local database user
Not used with -f flag
-P local database password
Not used with -f flag
-N local database name
(Optional, assumes external db name)
EOF
}
FILENAME=
CONNECTION=
EXTUSER=
EXTPASS=
EXTDB=
LOCUSER=
LOCPASS=
LOCDB=
while getopts "hf:c:u:p:n:U:P:N:" OPTION
do
case $OPTION in
h)
usage
exit 1
;;
f)
FILENAME=$OPTARG
;;
c)
CONNECTION=$OPTARG
;;
u)
EXTUSER=$OPTARG
;;
p)
EXTPASS=$OPTARG
;;
n)
EXTDB=$OPTARG
;;
U)
LOCUSER=$OPTARG
;;
P)
LOCPASS=$OPTARG
;;
N)
LOCDB=$OPTARG
;;
?)
usage
exit
;;
esac
done
if [[ -z $CONNECTION ]] || [[ -z $EXTUSER ]] || [[ -z $EXTPASS ]] || [[ -z $EXTDB ]]
then
usage
exit 1
fi
if [[ $FILENAME ]]
then
echo "Saving DB Dump to '$FILENAME'"
ssh $CONNECTION "mysqldump -u$EXTUSER -p$EXTPASS $EXTDB" > $FILENAME
echo "Done."
exit 1
elif [[ -z $LOCUSER ]] || [[ -z $LOCPASS ]]
then
usage
exit 1
fi
echo "Retrieving current $EXTDB dump"
ssh $CONNECTION "mysqldump -u$EXTUSER -p$EXTPASS $EXTDB" > tmp.sql
if [[ -z $LOCDB ]]
then
LOCDB=$EXTDB
fi
echo "Dropping local $LOCDB and recreating"
mysql -u$LOCUSER -p$LOCPASS -e "drop database if exists $LOCDB; create database $LOCDB;"
echo "Importing new $LOCDB database"
mysql -D $LOCDB -u$LOCUSER -p$LOCPASS < tmp.sql
echo "----------------"
echo "Import Complete. Removing SQL file."
rm tmp.sql
exit 1
@cmbirk
Copy link
Author

cmbirk commented Jan 11, 2013

The next iteration will be interactive instead of argument based

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment