简体   繁体   中英

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'

只需使用 \ 转义 $。

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

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.

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM