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

Could anyone explain to me why echo 'test \'hi\'' > test doesn't work? It doens't write hi to the file test. The single quotes seem to be properly escaped, aren't they?


share|improve this question
Is this a particular language or anything? and this would probably be a StackOverflow question.. – cutrightjm Mar 19 '12 at 16:58
the reason for the error: the 2nd quote ends the string starting at the 1st quote; the 3rd quote is escaped so it's just a character; and the 4th quote does not have a match to end the string. – glenn jackman Mar 19 '12 at 19:44
up vote 3 down vote accepted

You can't embed single quotes within single-quoted strings. Instead, you have to place and escape the single quotes outside of the quoted string.

For example:

echo 'test '\''hi'\' > test

This writes:

  • test from 'test ' (with one space after the word test - the syntax highlighting isn't reflecting that here...)
  • passes \' to be written as a literal quote
  • writes hi from 'hi'.
  • passes \' to be written as a literal quote
  • results in test 'hi' being written to a file called test.
share|improve this answer
echo "test 'hi'" > test will also work – glenn jackman Mar 19 '12 at 18:29
@glennjackman - Agreed, but it's important to understand that it can be done without switching quote types - as what would happen if you needed to display both? These are also fundamentally different, as double quotes will allow variable substitutions to be expanded, where as single quotes will not expand them. – ziesemer Mar 19 '12 at 19:07
True, it depends on what the OP wants. But readability/maintainability needs to be considered. – glenn jackman Mar 19 '12 at 19:47
Thanks. The text hi is normally an user-inputted variable, so that's why it with quotes (passed from PHP with escapeshellcmd). – Devator Mar 19 '12 at 21:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .