Bash (Scripting) - local and remote variables with SSH

by
Jeremy Canfield |
Updated: November 25 2024
| Bash (Scripting) articles
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, and echo properly displays the value of both "a" and "b" in the console.
~]$ a="Hello"; ssh root@server2 "b="World"; echo $a; echo \$b;"
Hello
World
I do not believe there is a way with Bash to create a variable in the SSH session and then use the variable by the local host.
Here is a bit of a more practical example, where each $ character is escaped.
ssh root@server2 "for directory in \$(find /tmp -mindepth 1 -maxdepth 1 -type d); do echo \$directory; done;"
Did you find this article helpful?
If so, consider buying me a coffee over at