如何使用ssh和bash脚本将本地变量传递到远程? [英] How to pass local variable to remote using ssh and bash script?

查看:896
本文介绍了如何使用ssh和bash脚本将本地变量传递到远程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ssh remotecluster 'bash -s' << EOF
> export TEST="sdfsd"
> echo $TEST
> EOF

这不会打印任何内容.

即使我将变量存储到文件中并将其复制到远程,它仍然不起作用.

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 ?

已在推荐答案

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屋!

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