Search code examples
bashsshenvironment-variablesdouble-quotessingle-quotes

Executing multiple commands with ssh, including evaluation of environment variables on the remote machine


I sometimes use ssh to run multiple commands on a remote host like this:

ssh my_user@my_host "command1; command2"

utilizing double quotes to send both commands to the remote machine.

Now I would like to access an environment variable in one or both of the commands.
Here is a simplified example that illustrates what I have tried:

ssh my_user@my_host "echo $USER; echo $HOSTNAME"

This echos my user/hostname on the local machine, whereas I would like to see the names on the remote machine instead.

Using single quotes I can achieve what I want for a single command as follows:

ssh my_user@my_host echo '$USER'

but I don't get the behavior I want when I use single quotes inside the double quotes like this:

ssh my_user@my_host "echo '$USER'; echo '$HOSTNAME'"

How can I get the behavior I want with both commands being executed from a single ssh commmand?

(Please note that my actual commands are more complicated... I do realize that I can get both variables in a single command for my toy example as below, but this does not solve my real problem):

ssh my_user@my_host echo '$USER' '$HOST'


Solution

  • Just escape the $ using \.

    ssh my_user@my_host "echo \$USER; echo \$HOSTNAME"