How to escape a single quote in single quote string in Bash?

后端 未结 3 1096
广开言路
广开言路 2020-11-30 02:58

I want to display a string in Bash like this

I\'m a student

Of course you can do it like this

echo \"I\'m a student\"
<         


        
相关标签:
3条回答
  • 2020-11-30 03:26

    The "ugly" solution mentioned by Glenn Jackman should actually be listed as a top level answer. It works well and is actually beautiful in some situations.

    'I'"'"'m a student'
    

    This ends the single quoted string after I then immediately starts a double quoted string containing a single quote and then starts another single quoted string. Bash then concatenates all contiguous strings into one.

    Beautiful!

    0 讨论(0)
  • 2020-11-30 03:26

    The example below works because the escaped single quote \' is technically between two single-quoted arguments

    echo 'I'\''m a student'
    
    0 讨论(0)
  • 2020-11-30 03:37
    echo 'I\'m a student'
    

    does not work. But the following works:

    echo $'I\'m a student'
    

    From the man page of bash:

    A single quote may not occur between single quotes, even when preceded by a backslash.
    ....
    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.

    0 讨论(0)
提交回复
热议问题