Linux 如何在 SSH 命令中同时包含本地和远程变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13826149/
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
How have both local and remote variable inside an SSH command
提问by Sepehr Samini
How can I have both local and remote variable in an ssh command? For example in the following sample code:
如何在 ssh 命令中同时拥有本地和远程变量?例如在以下示例代码中:
A=3;
ssh host@name "B=3; echo $A; echo $B;"
I have access to A but B is not accessible.
我可以访问 A,但无法访问 B。
But in the following example:
但在下面的例子中:
A=3;
ssh host@name 'B=3; echo $A; echo $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和B?
采纳答案by sampson-chen
I think this is what you want:
我认为这就是你想要的:
A=3;
ssh host@name "B=3; echo $A; echo $B;"
When you use double-quotes:
当您使用双引号时:
Your shell does auto expansion on variables prefixed with $, so in your first example, when it sees
您的 shell 对前缀为 的变量进行自动扩展$,因此在您的第一个示例中,当它看到
ssh host@name "B=3; echo $A; echo $B;"
bash expands it to:
bash 将其扩展为:
ssh host@name "B=3; echo 3; echo ;"
and thenpasses host@name "B=3; echo 3; echo ;"as the argument to ssh. This is because you defined Awith A=3, but you never defined B, so $Bresolves to the empty string locally.
并然后传递host@name "B=3; echo 3; echo ;"作为参数ssh。这是因为你定义A有A=3,但你永远不定义B,所以$B本地解析为空字符串。
When you use single-quotes:
当您使用单引号时:
Everything enclosed by single-quotes are interpreted as string-literals, so when you do:
用单引号括起来的所有内容都被解释为字符串文字,所以当你这样做时:
ssh host@name 'B=3; echo $A; echo $B;'
the instructions B=3; echo $A; echo $B;will be run once you log in to the remote server. You've defined Bin the remote shell, but you never told it what Ais, so $Awill resolve to the empty string.
B=3; echo $A; echo $B;一旦您登录到远程服务器,这些说明就会运行。您已B在远程 shell 中定义,但您从未告诉它是什么A,因此$A将解析为空字符串。
So when you use \$, as in the solution:
所以当你使用时\$,就像在解决方案中一样:
\$means to interpret the $character literally, so we send literally echo $Bas one of the instructions to execute remotely, instead of having bash expand $Blocally first. What we end up telling sshto do is equivalent to this:
\$意思是$从字面上解释字符,所以我们从字面上发送echo $B作为远程执行的指令之一,而不是让 bash$B首先在本地展开。我们最终告诉ssh要做的相当于:
ssh host@name 'B=3; echo 3; echo $B;'

