Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 sh -c doesn't handle the echo starting command correctly? It outputs a blank line.
  2. Why is SHELL set to /bin/bash even with sh -c?
share|improve this question

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: http://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"'
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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