4

I am connecting to remote-server from localhost, and I want to execute command on remote-server.

works as expected:

ssh remote-server "hostname"
remote-server

I am confused. Why does this return local hostname, instead of the hostname of remote server?

ssh remote-server "print $HOST"
localhost

2 Answers 2

8

Your second code example:

ssh remote-server "print $HOST"
localhost

will be flagged by the great Shellcheck tool with the diagnostic SC2029:

Bash expands all arguments that are not escaped/singlequoted. This means that the problematic code is identical to

ssh host "echo clienthostname"

and will print out the client's hostname, not the server's hostname.

By escaping the $ in $HOSTNAME, it will be transmitted literally and evaluated on the server instead.

By using

ssh host "print \$HOST"

or

ssh host 'print $HOST'

you can prevent your local shell from expanding host and instead have the shell on remote-server expand it.

1
6

Because you're using double-quotes, so the shell evaluates $HOST before it executes the command and launches ssh, so you send the command "print localhost" to the remote server.

Use single quotes instead:

shadur@proteus:~$ ssh axiom "echo $HOSTNAME"
shadur@axiom's password:
proteus

shadur@proteus:~$ ssh axiom 'echo $HOSTNAME'
shadur@axiom's password:
axiom

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .