How to escape quotes in shell?

  • 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.

    +1 for "Of course, this doesn't produce the right results". `bash` is well on the way to making me mad.

  • SiegeX

    SiegeX Correct answer

    9 years ago

    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     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

    Overkill. In most cases you do not need to use string literal syntax.

License under CC-BY-SA with attribution

Content dated before 6/26/2020 9:53 AM