How to pass local variable to remote using ssh and

2020-03-26 05:15发布

问题:

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

回答1:

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).

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.

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.

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


回答2:

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