简体   繁体   中英

How to pass variables to SSH command in bash script

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.

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;"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM