How to escape single quotes within single quoted strings

前端 未结 23 2046
说谎
说谎 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:58

    Since Bash 2.04 syntax $'string' (instead of just 'string'; warning: do not confuse with $('string')) is another quoting mechanism which allows ANSI C-like escape sequences and do expansion to single-quoted version.

    Simple example:

      $> echo $'aa\'bb'
      aa'bb
    
      $> alias myvar=$'aa\'bb'
      $> alias myvar
      alias myvar='aa'\''bb'
    

    In your case:

    $> alias rxvt=$'urxvt -fg \'#111111\' -bg \'#111111\''
    $> alias rxvt
    alias rxvt='urxvt -fg '\''#111111'\'' -bg '\''#111111'\'''
    

    Common escaping sequences works as expected:

    \'     single quote
    \"     double quote
    \\     backslash
    \n     new line
    \t     horizontal tab
    \r     carriage return
    

    Below is copy+pasted related documentation from man bash (version 4.4):

    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
        \?     question mark
        \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)
        \uHHHH the Unicode (ISO/IEC 10646) character whose value is 
               the hexadecimal value HHHH (one to four hex digits)
        \UHHHHHHHH the Unicode (ISO/IEC 10646) character whose value 
                   is the hexadecimal value HHHHHHHH (one to eight 
                   hex digits)
        \cx    a control-x character
    

    The expanded result is single-quoted, as if the dollar sign had not been present.


    See Quotes and escaping: ANSI C like strings on bash-hackers.org wiki for more details. Also note that "Bash Changes" file (overview here) mentions a lot for changes and bug fixes related to the $'string' quoting mechanism.

    According to unix.stackexchange.com How to use a special character as a normal one? it should work (with some variations) in bash, zsh, mksh, ksh93 and FreeBSD and busybox sh.

提交回复
热议问题