How to escape single quotes within single quoted strings

前端 未结 23 2184
说谎
说谎 2020-11-21 06:20

Let\'s say, you have a Bash alias like:

alias rxvt=\'urxvt\'

which works fine.

However:



        
23条回答
  •  时光说笑
    2020-11-21 06:39

    IMHO the real answer is that you can't escape single-quotes within single-quoted strings.

    Its impossible.

    If we presume we are using bash.

    From bash manual...

    Enclosing characters in single quotes preserves the literal value of each
    character within the quotes.  A single quote may not occur
    between single quotes, even when preceded by a backslash.
    

    You need to use one of the other string escape mechanisms " or \

    There is nothing magic about alias that demands it use single quotes.

    Both the following work in bash.

    alias rxvt="urxvt -fg '#111111' -bg '#111111'"
    alias rxvt=urxvt\ -fg\ \'#111111\'\ -bg\ \'#111111\'
    

    The latter is using \ to escape the space character.

    There is also nothing magic about #111111 that requires single quotes.

    The following options achieves the same result the other two options, in that the rxvt alias works as expected.

    alias rxvt='urxvt -fg "#111111" -bg "#111111"'
    alias rxvt="urxvt -fg \"#111111\" -bg \"#111111\""
    

    You can also escape the troublesome # directly

    alias rxvt="urxvt -fg \#111111 -bg \#111111"
    

提交回复
热议问题