如何使用 ssh 和 bash 脚本将本地变量传递给远程?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15778403/
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 to pass local variable to remote using ssh and bash script?
提问by tomriddle_1234
ssh remotecluster 'bash -s' << EOF
> export TEST="sdfsd"
> echo $TEST
> EOF
This prints nothing.
这不打印任何内容。
Also it still does not work even if I store the variable into file and copy it to remote.
即使我将变量存储到文件中并将其复制到远程,它仍然不起作用。
TEST="sdfsdf"
echo $TEST > temp.par
scp temp.par remotecluster
ssh remotecluster 'bash -s' << EOF
> export test2=`cat temp.par`
> echo $test2
> EOF
Still prints nothing.
仍然没有打印任何内容。
So my question is how to pass local variable to the remote machine as a variable ?
所以我的问题是如何将本地变量作为变量传递给远程机器?
Answers have been give in this
答案已在此给出
采纳答案by carlo
The variable assignment TEST="sdfsd"given in the here document is no real variable assignment, i. e. the variable assignment will actually not be performed directly in the declaration / definition of the here document (but later when the here document gets evaluated by a shell).
TEST="sdfsd"here 文档中给出的变量赋值并不是真正的变量赋值,即变量赋值实际上不会在 here 文档的声明/定义中直接执行(但稍后当 here 文档被 shell 评估时)。
In addition, the $TESTvariable contained in an unescaped or unquoted here document will be expanded by the local shellbefore the local shell executes the sshcommand.
The result is that $TESTwill get resolved to the empty string if it is not defined in the local shell beforethe sshcommand or the here document respectively.
此外,该$TEST变量包含在转义或不带引号这里文件将被扩大本地shell本地shell执行之前ssh的命令。结果是,$TEST如果在命令或 here 文档之前没有在本地 shell 中定义它,它将被解析为空字符串ssh。
As a result, the variable assignment export TEST="sdfsd"in the here document will not take effect in the local shell, but first be sent to the shell of the remote host and only there be expanded, hence your prints nothingexperience.
这样一来,export TEST="sdfsd"here文档中的变量赋值在本地shell中不会生效,而是先发送到远程主机的shell中,才在那里展开,所以你打印出来的没什么经验。
The solution is to use an escaped or single-quoted here document, <<\EOFor <<'EOF'; or only escape the \$TESTvariable in the here document; or just define the $TESTvariable before the sshcommand (and here document).
解决方案是使用转义或单引号 here 文档,<<\EOF或<<'EOF'; 或仅转义\$TEST此处文档中的变量;或者只是$TEST在ssh命令之前定义变量(和这里的文档)。
# prints sdfsd
export TEST="sdfsd"
ssh localhost 'bash -s' << EOF
echo $TEST
EOF
# prints sdfsd
ssh localhost 'bash -s' << EOF
export TEST="sdfsd"
echo $TEST
EOF
# prints sdfsd
ssh localhost 'bash -s' <<'EOF'
export TEST="sdfsd"
echo $TEST
EOF
回答by Jalal Hajigholamali
export variable, ssh send exported(environment) variables to server export VAR=test ssh -v 127.0.0.1 echo $VAR test above commands and see result
导出变量,ssh 将导出的(环境)变量发送到服务器 export VAR=test ssh -v 127.0.0.1 echo $VAR test 以上命令并查看结果

