bash 通过 SSH 运行“导出”命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4663615/
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
Run 'export' command Over SSH
提问by aaronstacy
When I run the following from my bashshell:
当我从我的bashshell运行以下命令时:
bash -c '(export abc=123 && echo $abc)'
The output is "123". But when I run it over ssh:
输出为“123”。但是当我运行它时ssh:
ssh remote-host "bash -c '(export abc=123 && echo $abc)'"
There is no output. Why is this? Is there a way around this? That is, is there a way to set an environment variable for a command I run over ssh?
没有输出。为什么是这样?有没有解决的办法?也就是说,有没有办法为我运行的命令设置环境变量ssh?
Note: When I replace echo $abcwith something standard like echo $USERthe sshcommand prints out the username on the remote machine as expected since it is already set.
注意:当我echo $abc用一些标准echo $USER的东西替换时,ssh命令会按预期打印出远程机器上的用户名,因为它已经设置好了。
I am running RHEL 5 Linux with OpenSSH 4.3
我正在使用 OpenSSH 4.3 运行 RHEL 5 Linux
回答by Marcus Borkenhagen
That is because when using
那是因为当使用
ssh remote-host "bash -c '(export abc=123 && echo $abc)'"
the variable gets expanded by the localshell (as it is the case with $USER) before sshexecutes. Escape the $by using \$and it should do fine
变量在执行之前被本地shell扩展(就像 的情况一样$USER)ssh。$通过使用转义\$它应该没问题
ssh remote-host "bash -c '(export abc=123 && echo $abc)'"
On a side note:
附带说明:
- You don't need to export just for this.
- You don't need to wrap it in ()
- 您不需要为此而导出。
- 你不需要把它包装在 ()
Like so:
像这样:
ssh remote-host "bash -c 'abc=123 && echo $abc'"
Heck, you can even leave out the bash -c ...stuff, as the ssh manpage states:
哎呀,您甚至可以省略这些bash -c ...内容,如 ssh 联机帮助页所述:
If command is specified, it is executed on the remote host instead of a login shell.
如果指定了命令,它将在远程主机上执行,而不是在登录 shell 上执行。
But these may be specific to your task ;)
但这些可能特定于您的任务;)

