Tim Bezhashvyly
Tim Bezhashvyly

Reputation: 9100

Evaluating bash variable on remote host

I have a hard time evaluating variable on the remote host.

myCmd='echo $myVar'
myVar=test
eval $myCmd                                 # Outputs "test" 

ssh -T -p <port> <user>@<host> <<ENDSSH
  echo $myVar                               # Outputs "test"
  eval $myCmd                               # Outputs empty string
ENDSSH

It is a requirement that myCmd variable is instantiated before myVar. That's why single quotes are used to freeze string evaluation.

As the example above shows myVar is accessible from remote host but not used in myCmd evaluation.

Upvotes: 3

Views: 106

Answers (1)

Rambo Ramon
Rambo Ramon

Reputation: 1034

It is because myVar is not available in the heredoc. The variables are replaced beforehand and the echo works because it is literally echo test. The eval part is eval echo $myVar but like I said, myVar is not defined in this context and therfore it is literally eval echo.

Have a look at this question for some more details. Why does bash -c "false; echo $?" print 0?

A solution could be copying the variable to the context of the heredoc.

myCmd='echo $myVar'
myVar=test

ssh -T -p <port> <user>@<host> <<ENDSSH
  myVar=$myVar
  eval $myCmd
ENDSSH

I don't know if this is suitable for you particular case but it is at least a starting point.

Another solution, and probably a better one, is to expand the expression first and then passing it to the heredoc.

myCmd='echo $myVar'
myVar=test
myCmd=$(eval echo $myCmd)

ssh -T -p <port> <user>@<host> <<ENDSSH
  eval $myCmd
ENDSSH

Upvotes: 4

Related Questions