Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluating bash variable on remote host

Tags:

bash

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.

like image 906
user487772 Avatar asked Feb 21 '26 03:02

user487772


1 Answers

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
like image 170
Rambo Ramon Avatar answered Feb 23 '26 21:02

Rambo Ramon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!