Super User is a question and answer site for computer enthusiasts and power users. 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

This is my shell command:

sudo sh -c "echo "#" > /file"

But it doensn't work but this does work:

sudo sh -c "echo "hi" > /file"

How can I fix this, because the # needs to be in it.

share|improve this question

migrated from May 11 '13 at 18:29

This question came from our site for professional and enthusiast programmers.

(Just a comment on "why?"; the given answers address "how to fix".) Double quotes don't nest. The # isn't part of the argument to the -c option; only "echo " is. The # simply marks the beginning of a comment on the line. – chepner May 11 '13 at 15:55
It needs to be in the file! – Daan Lemmen May 11 '13 at 16:09
up vote 5 down vote accepted

Use 'hard' quotes for tricky characters:

sudo sh -c "echo '#' > /file"
share|improve this answer
Thanks, now it's working! – Daan Lemmen May 11 '13 at 15:51
Has nothing to do with the double quotes like it would if this was about a $ character. sudo sh -c 'echo "#" > /file' would work as well. It's just that the original script line uses the same quotes on both levels without escaping, resulting in sudo sh -c "echo ", with the rest being a comment (possibly thanks to the bash option interactive_comments) – Daniel Beck May 11 '13 at 18:36

If you don't want to use different quotes for just one character, you could also escape the hash character:

sudo sh -c "echo "\#" > /file"

Like in many scripting languages, shell commands interpret a hash character (#) as the beginning of a comment.

share|improve this answer
Doesn't work for me! – Daan Lemmen May 11 '13 at 15:56
It doesn't work because all of the quotes are removed before the string is passed to sudo (and thence to sh -c). Essentially, it's executing the command echo # > /file, which is equivalent to just echo. – Gordon Davisson May 11 '13 at 17:41

You must log in to answer this question.