3

I am new to bash scripting, and am attempting write a script to sync my local Wordpress database with a remote one. Here it is:

#!/bin/sh 

RUSER=example-admin 
RHOST=ftp.example.com 
RDBUSER=wp_admin
RDB=wp_db
RDBHOST=localhost
RBAK=.backup/latest-remote-db.mssql 

LUSER=root
LPASS=root
LHOST=localhost
LDB=wp_db
LBAK=.backup/latest-local-db.mssql 

#dump the contents of my local database
mysqldump -u$LUSER -p$LPASS -h $LHOST $LDB > $LBAK

#upload my local database to remote
scp $LBAK $RUSER@$RHOST:~/.backup/

#login to remote host, backup remote database, delete the remote database then recreate it, restore it with the contents of my local database
ssh $RUSER@$RHOST 'mysqldump -uwp_admin -h localhost wp_db > ~/.backup/latest-remote-db.mssql; mysql -uwp_admin -h localhost -Bse "show databases; drop database wp_db; create database wp_db;"; mysql -uwp_admin -h localhost wp_db < ~/.backup/latest-local-db.mssql;'

The above works fine, yet I'm not satisfied with the final ssh command because all the values are hard-coded. I would prefer to use something like this:

ssh $RUSER@$RHOST 'mysqldump -u$RDBUSER -h $RDBHOST $RDB > ~/$RBAK; mysql -u$RDBUSER -h $RDBHOST -Bse "drop database $RDB; create database $RDB;"; mysql -u$RDBUSER -h $RDBHOST $RDB < ~/$LBAK;'

However this obviously does not work, because the all the variables are trapped inside quotes and therefore don't get substituted. Can anybody advise on a better way to achieve this? I considered executing a separate script on the remote end to handle all the mysql commands, yet that strikes me as more inefficient.

3
  • 1
    Is there a reason to use single quote ' brackets, which do not expand bash variable, instead of double quote ones "? Details on difference : stackoverflow.com/questions/6697753/… Commented Nov 1, 2012 at 11:33
  • bbaja42, that's the answer! Thank you so much for your help. Commented Nov 1, 2012 at 11:47
  • The next step for you should be to accept dogbane's solution. Commented Nov 1, 2012 at 12:42

1 Answer 1

2

Use double-quotes for the outermost quotes so that variables are expanded. Use single quotes inside.

Try this:

ssh $RUSER@$RHOST "mysqldump -u$RDBUSER -h $RDBHOST $RDB > ~/$RBAK; mysql -u$RDBUSER -h $RDBHOST -Bse 'drop database $RDB; create database $RDB;'; mysql -u$RDBUSER -h $RDBHOST $RDB < ~/$LBAK;"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.