33

How can I have both local and remote variable in an ssh command? For example in the following sample code:

A=3;
ssh host@name "B=3; echo $A; echo $B;"

I have access to A but B is not accessible.

But in the following example:

A=3;
ssh host@name 'B=3; echo $A; echo $B;'

I don't have A and just B is accessible.

Is there any way that both A and B be accessible?

1
  • Looks like A is accessible in the 2nd and not B. Is this right? Commented Dec 11, 2012 at 18:36

1 Answer 1

78

I think this is what you want:

A=3;
ssh host@name "B=3; echo $A; echo \$B;"

When you use double-quotes:

Your shell does auto expansion on variables prefixed with $, so in your first example, when it sees

ssh host@name "B=3; echo $A; echo $B;"

bash expands it to:

ssh host@name "B=3; echo 3; echo ;"

and then passes host@name "B=3; echo 3; echo ;" as the argument to ssh. This is because you defined A with A=3, but you never defined B, so $B resolves to the empty string locally.


When you use single-quotes:

Everything enclosed by single-quotes are interpreted as string-literals, so when you do:

ssh host@name 'B=3; echo $A; echo $B;'

the instructions B=3; echo $A; echo $B; will be run once you log in to the remote server. You've defined B in the remote shell, but you never told it what A is, so $A will resolve to the empty string.


So when you use \$, as in the solution:

\$ means to interpret the $ character literally, so we send literally echo $B as one of the instructions to execute remotely, instead of having bash expand $B locally first. What we end up telling ssh to do is equivalent to this:

ssh host@name 'B=3; echo 3; echo $B;'
Sign up to request clarification or add additional context in comments.

2 Comments

You can check the generated command follows A=3; ssh -v host@name "B=5; echo $A; echo \$B;" 2>&1 | grep -A 2 'Sending command' or sh -xc 'A=3; ssh host@name "B=5; echo $A; echo \$B;"'.
Note that this can delay variable expansion, too. ssh host@name 'B=\$(find . -name "*.txt"); echo \$B'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.