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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With