Bash – How to Escape Quotes in the Bash Shell

escape-charactersquotingshell

I'm having trouble with escaping characters in bash. I'd like to escape single and double quotes while running a command under a different user. For the purposes of this question let's say I want to echo the following on the screen:

'single quote phrase' "double quote phrase"

How can I escape all the special chars, if I also need to switch to a different user:

sudo su USER -c "echo \"'single quote phrase' \"double quote phrase\"\""

Of course, this doesn't produce the right result.

Best Answer

You can use the following string literal syntax:

> echo $'\'single quote phrase\' "double quote phrase"'
'single quote phrase' "double quote phrase"

From man bash

Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard. Backslash escape sequences, if present, are decoded as follows:

          \a     alert (bell)
          \b     backspace
          \e
          \E     an escape character
          \f     form feed
          \n     new line
          \r     carriage return
          \t     horizontal tab
          \v     vertical tab
          \\     backslash
          \'     single quote
          \"     double quote
          \nnn   the eight-bit character whose value is the octal value nnn (one to three digits)
          \xHH   the eight-bit character whose value is the hexadecimal value HH (one or two hex digits)
          \cx    a control-x character
Related Question