'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 1:[1]

Just escape the $ using \.

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

Solution 2:[2]

You can put the entire command to be run in single quotes, like so:

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

That will prevent your shell from substituting the environment variable values before passing them to the remote machine, but when they get to the remote machine they are unquoted so they get evaluated there.

Solution 3:[3]

Thanks to Guilherme Richter. That solution works! I will accept it once the 5 minutes has passed. I wanted to document that in the meantime I found another solution that avoids the double quotes instead of avoiding the single quotes by escaping the semicolon:

ssh user@host echo '$USER' \; echo '$USER'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Guilherme Richter
Solution 2 Esther
Solution 3 Jed