SSH命令中如何同时包含本地和远程变量 [英] How have both local and remote variable inside an SSH command

查看:539
本文介绍了SSH命令中如何同时包含本地和远程变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆