Shell variable expansion across ssh sessions

ssh allows you to run a command on a remote machine. You may want to use a shell variable in a remote command. You have to be aware of when that variable gets evaluated.

This session started with me interactively logged in on a remote system called f34-kernel-test. We’ll call this the server, and the system from which I logged in we’ll call the client. My goal is to type the command on the client, hit enter, and see the hostname of the remote system.

[fedora@f34-kernel-test ~]$ echo $HOSTNAME
f34-kernel-test.novalocal
[fedora@f34-kernel-test ~]$ exit
logout
Connection to 10.76.97.231 closed.
[ayoung@ayoung-home linux]$ echo $HOSTNAME
ayoung-home.amperecomputing.com
[ayoung@ayoung-home linux]$ ssh fedora@10.76.97.231   echo $HOSTNAME
ayoung-home.amperecomputing.com
[ayoung@ayoung-home linux]$ ssh fedora@10.76.97.231   "echo $HOSTNAME"
ayoung-home.amperecomputing.com
[ayoung@ayoung-home linux]$ ssh fedora@10.76.97.231   "echo '$HOSTNAME'"
ayoung-home.amperecomputing.com
[ayoung@ayoung-home linux]$ ssh fedora@10.76.97.231   "echo \$HOSTNAME"
f34-kernel-test.novalocal

Note that all of the quoted options failed to prevent the variable expansion from happening on the client system. The only approach which worked here was to escape the slash.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.