SSH命令中如何同时包含本地和远程变量 [英] How have both local and remote variable inside an SSH command
问题描述
如何在ssh命令中同时包含本地和远程变量?例如下面的示例代码:
How can I have both local and remote variable in an ssh command? For example in the following sample code:
A=3;
ssh host@name "B=3; echo $A; echo $B;"
我可以访问A,但无法访问B.
I have access to A but B is not accessible.
但是在以下示例中:
A=3;
ssh host@name 'B=3; echo $A; echo $B;'
我没有A,只能访问B.
I don't have A and just B is accessible.
是否可以同时访问A和B?
Is there any way that both A and B be accessible?
推荐答案
我认为这是您想要的:
A=3;
ssh host@name "B=3; echo $A; echo \$B;"
使用双引号:
您的shell会自动对前缀为$
的变量进行自动扩展,因此在您的第一个示例中,当它看到
Your shell does auto expansion on variables prefixed with $
, so in your first example, when it sees
ssh host@name "B=3; echo $A; echo $B;"
bash将其扩展为:
bash expands it to:
ssh host@name "B=3; echo 3; echo ;"
和然后将host@name "B=3; echo 3; echo ;"
作为参数传递给ssh
.这是因为您用A=3
定义了A
,但从未定义过B
,所以$B
在本地解析为空字符串.
and then passes host@name "B=3; echo 3; echo ;"
as the argument to ssh
. This is because you defined A
with A=3
, but you never defined B
, so $B
resolves to the empty string locally.
使用单引号:
用单引号引起来的所有内容都被解释为字符串文字,因此当您这样做时:
Everything enclosed by single-quotes are interpreted as string-literals, so when you do:
ssh host@name 'B=3; echo $A; echo $B;'
一旦登录到远程服务器,便会执行B=3; echo $A; echo $B;
指令.您已经在远程外壳程序中定义了B
,但是您从未告诉过A
是什么,因此$A
将解析为空字符串.
the instructions B=3; echo $A; echo $B;
will be run once you log in to the remote server. You've defined B
in the remote shell, but you never told it what A
is, so $A
will resolve to the empty string.
因此,当您使用\$
时,如在解决方案中一样:
So when you use \$
, as in the solution:
\$
意味着按字面意义解释$
字符,因此我们按字面意义将echo $B
发送为远程执行的指令之一,而不是先在本地进行bash扩展$B
.我们最终告诉ssh
要做的事情等效于此:
\$
means to interpret the $
character literally, so we send literally echo $B
as one of the instructions to execute remotely, instead of having bash expand $B
locally first. What we end up telling ssh
to do is equivalent to this:
ssh host@name 'B=3; echo 3; echo $B;'
这篇关于SSH命令中如何同时包含本地和远程变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!