Evaluating bash variable on remote host

I have a complex time variable on a 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

      

Requiring the variable to be myCmd

created before myVar

. It uses single quotes to freeze the evaluation of the string.

As shown in the example above, it myVar

is accessible from a remote host, but not used in the evaluation myCmd

.

+3


source to share


1 answer


This is because it is myVar

not available in the heredoc. The variables are replaced beforehand and the echo works because it's literal echo test

. The Eval part eval echo $myVar

, but as I said, myVar is not defined in this context, and therefore literally eval echo

.

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

The solution can copy the variable into the heredoc context.

myCmd='echo $myVar'
myVar=test

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

      



I don't know if this is appropriate for your specific case, but this is at least a starting point.

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

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

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

      

+4


source







All Articles