3

I am trying to run a few commands through ssh and getting confused with the behavior of sh -c:

ssh myhost sh -c 'echo starting; who -b; date; echo $SHELL'

Output (note: the echo's output is just a blank line!)

         system boot  2016-12-22 20:22
Thu Jan 26 06:12:52 UTC 2017
/bin/bash

Without sh -c I get the correct output:

ssh myhost 'echo starting; who -b; date; echo $SHELL'

Output:

starting
         system boot  2016-12-22 20:22
Thu Jan 26 06:18:28 UTC 2017
/bin/bash

Questions:

  1. Why doesn't sh -c handle the echo starting command correctly? It outputs a blank line.
  2. Why is SHELL set to /bin/bash even with sh -c?
7

There are a couple different unintuitive things going on here.

First of all, your command to the remote host is parsed as

(sh -c echo starting); who -b; date; echo $SHELL

The outer quotes are stripped away leaving you with only echo starting run in sh which is why $SHELL is set to /bin/bash.

Secondly, "starting" isn't printed for the reasons stated in this answer: https://unix.stackexchange.com/a/253424

However, you can fix both of these problems by simply wrapping the command in another set of quotes, leaving you with

ssh myhost sh -c '"echo starting; who -b ; date; echo $SHELL"'

Though I would argue it's more clear if you move the single quotes out to encompass the sh command:

ssh myhost 'sh -c "echo starting; who -b ; date; echo $SHELL"'
| improve this answer | |
  • 1
    The $SHELL would be expanded by the login shell of the remote user as it's between double quotes (and assuming that shell is Bourne-like or csh-like or fish). You'd need to escape the $ if you wanted the $SHELL to be expanded by sh: ssh myhost 'sh -c "echo starting; who -b ; date; echo \$SHELL"' – Stéphane Chazelas Jan 26 '17 at 12:27

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