Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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 stackoverflow.com May 11 '13 at 18:29

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

3  
(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
add comment

2 Answers

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
3  
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
add comment

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
2  
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
add comment

Your Answer

 
discard

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