bash 如何在bash脚本中将变量传递给SSH命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13176099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:40:26  来源:igfitidea点击:

How to pass variables to SSH command in bash script

mysqlwordpressbashunixssh

提问by JP Lew

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:

我是 bash 脚本的新手,正在尝试编写一个脚本来将我的本地 Wordpress 数据库与远程数据库同步。这里是:

#!/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 sshcommand because all the values are hard-coded. I would prefer to use something like this:

以上工作正常,但我对最终ssh命令不满意,因为所有值都是硬编码的。我更喜欢使用这样的东西:

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 mysqlcommands, yet that strikes me as more inefficient.

然而,这显然不起作用,因为所有变量都被困在引号内,因此不会被替换。有人可以建议更好的方法来实现这一目标吗?我考虑在远程端执行一个单独的脚本来处理所有mysql命令,但我觉得这效率更低。

采纳答案by dogbane

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