Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass local variable to remote using ssh and bash script?

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

like image 694
tomriddle_1234 Avatar asked Oct 04 '22 13:10

tomriddle_1234


1 Answers

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
like image 66
carlo Avatar answered Oct 18 '22 05:10

carlo