Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading