推荐答案
here文档中给出的变量赋值TEST="sdfsd"
不是真正的变量赋值,即. e.实际上,变量赋值实际上不会直接在here文档的声明/定义中执行(但稍后在shell对here文档进行评估时).
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).
此外,在本地外壳程序执行ssh
命令之前,本地外壳程序会扩展未在此处转义或未引用的文档中包含的$TEST
变量.
结果是,如果$TEST
分别在ssh
命令或here文档之前的本地外壳 中未定义,它将被解析为空字符串.
In addition, the $TEST
variable contained in an unescaped or unquoted here document will be expanded by the local shell before the local shell executes the ssh
command.
The result is that $TEST
will get resolved to the empty string if it is not defined in the local shell before the ssh
command or the here document respectively.
因此,here文档中的变量赋值export TEST="sdfsd"
在本地外壳程序中不会生效,但首先将其发送到远程主机的外壳程序中,然后才进行扩展,因此您的不打印任何内容经验.
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 nothing experience.
解决方案是使用转义的或单引号的此处文档<<\EOF
或<<'EOF'
;或仅转义此文档中的\$TEST
变量;或者只是在ssh
命令(和此处的文档)之前定义$TEST
变量.
The solution is to use an escaped or single-quoted here document, <<\EOF
or <<'EOF'
; or only escape the \$TEST
variable in the here document; or just define the $TEST
variable before the ssh
command (and here document).
# 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
这篇关于如何使用ssh和bash脚本将本地变量传递到远程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!