Skip to content

Instantly share code, notes, and snippets.

@otherjoel
Created September 26, 2017 13:58
Show Gist options
  • Save otherjoel/cf4a617380753fca116fa5f4cba66a57 to your computer and use it in GitHub Desktop.
Save otherjoel/cf4a617380753fca116fa5f4cba66a57 to your computer and use it in GitHub Desktop.
Simple script for syncing a folder and a database from a local dev environment to a production web server
#!/bin/bash
# This script will push any changes in a local dev environment (both files and
# a SQL database) to a prod server. It assumes you have passwordless SSH login
# set up on the remote server, and that you already have a database of the same
# name created on the remote server.
# This script stores SQL usernames and passwords in plain text. If you use it,
# make sure you store it in a safe place, don't include it in version control,
# and chmod its permissions to 700!
# Note: By default rsync does not delete remote copies of files that have been
# deleted locally. If you want to do this, add the --delete flag to the rsync
# command below.
#
echo "Syncing public web folder..."
rsync -ave ssh /var/www/html/ username@www.server.com:/var/www/mysite.com/public_html
# By default the SQL file generated by mysqldump will include instructions to drop
# each table and then recreate it and re-insert all the rows.
#
echo "Exporting database to local SQL file..."
mysqldump -u LOCAL_SQL_USER -pLOCAL_SQL_PASSWORD databasename > /home/me/db_dump.sql
# Note we upload the SQL file to a different remote directory than the public_html
# one used for the files above. Even though we're going to delete this file as soon
# as we're done with it, it's safer to never place it in a publicly accessible location.
#
echo "Uploading database export to www server over ssh..."
scp /home/me/db_dump.sql username@www.server.com:/remote-home/username/
echo "Updating database on www..."
# Execute commands on remote server; -T disables stupid warning about pseudo-tty allocation
ssh -T username@www.server.com << END
mysql -u REMOTE_SQL_USERNAME -pREMOTE_SQL_PASSWORD databasename < /remote-home/username/db_dump.sql
rm /remote-home/username/db_dump.sql
END
echo "Done!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment