1

I am trying to run commands on various nodes of our cluster automatically via a simples script. I have seen that I can run:

#!/bin/bash
echo "Machine: "$HOSTNAME;
ssh machine2 'echo Machine: $HOSTNAME;'
echo "Machine: "$HOSTNAME;

and I get the expected results:

Machine: machine1
Machine: machine2
Machine: machine1

However, I would like to run more complicated commands which will require variables, so I will need to use " instead of ' for the commands after the ssh. However, the ssh does not seem to work if I do it this way:

#!/bin/bash
echo "Machine: "$HOSTNAME;
ssh machine2 "echo Machine: $HOSTNAME;"
echo "Machine: "$HOSTNAME;

returns:

Machine: machine1
Machine: machine1
Machine: machine1

I have seen other questions which specifically state to run commands in this way using ", so I am at a loss for what is going on here.

2

I think what you're trying to ask is how to mix and match variables that much be evaluated locally with those that need to be evaluated remotely.

One option is to write a script for the actions to be handled remotely, thus encapsulating any reference to local variables so that the local host's quotes can't see them to expand them.

Another option for a really short segment is to mix your quotes, like this:

FRUIT=apples
ssh machine2 "echo Eating $FRUIT "'on $HOSTNAME'

Variables in the double-quoted segment will be evaluated locally (before the ssh is executed). Everything in the single-quoted segment will be treated as a literal. The two quoted strings will be concatenated to create the string echo Eating apples on $HOSTNAME and the result passed as a literal to be evaluated remotely.

2
  • Maybe this actually does answer my question - are you saying that in my second example when I only get the printouts of "Machine1", that the second printout is actually from machine2, but that it was passed the variable "Machine1" before the ssh took place? – drjrm3 Mar 12 '15 at 12:53
  • @Laurbert515 In your second example all outputs are from machine2. The $HOSTNAME had been evaluated on machine1 (it was in double quotes) and machine2 received the string echo Machine: machine1;, which it duly executed. – roaima Mar 12 '15 at 13:23
1

You can see for yourself:

[user@bluepc ~]$ echo "$HOSTNAME;"
bluepc;
[user@bluepc ~]$ echo '$HOSTNAME;'
$HOSTNAME;

Environment variables within single quotes are treated as strings.

In the case of ssh, if you use double quotes:

  • The string is substituted at local server.
  • The command is executed remotely.

if you use single quotes:

  • The string is passed as such into the remote server.
  • Substitution occurs remotely
  • Command is executed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.