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
[fedora@f34-kernel-test ~]$ exit
Connection to closed.
[ayoung@ayoung-home linux]$ echo $HOSTNAME
[ayoung@ayoung-home linux]$ ssh fedora@   echo $HOSTNAME
[ayoung@ayoung-home linux]$ ssh fedora@   "echo $HOSTNAME"
[ayoung@ayoung-home linux]$ ssh fedora@   "echo '$HOSTNAME'"
[ayoung@ayoung-home linux]$ ssh fedora@   "echo \$HOSTNAME"

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.