Create local and remote variables in bash SSH

Home > Search
  by

Let's say you have two Linux servers, server1.example.com and server2.example.com, and you want to create a variable on server1, then SSH into server2, create a variable on server2, and be able to use both variables. In this example, the "a" variable is created on server1, and the "b" variable is created on server2. The trick here is to escape the $ character in the SSH connection to server2.

~]$ a="Hello"; ssh root@server2 "b="World"; echo $a; echo \$b;"
Hello
World

 

If there are numerous $ characters in the SSH session, escape every $ character.

~]$ localHostname="$(hostname)"; ssh username@server2 "remoteHostname=\$(hostname); echo $localHostname; echo \$remoteHostname;"
server1.example.com
server2.example.com

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments