How to escape single quotes within single quoted strings

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

    Obviously, it would be easier simply to surround with double quotes, but where's the challenge in that? Here is the answer using only single quotes. I'm using a variable instead of alias so that's it's easier to print for proof, but it's the same as using alias.

    $ rxvt='urxvt -fg '\''#111111'\'' -bg '\''#111111'\'
    $ echo $rxvt
    urxvt -fg '#111111' -bg '#111111'
    

    Explanation

    The key is that you can close the single quote and re-open it as many times as you want. For example foo='a''b' is the same as foo='ab'. So you can close the single quote, throw in a literal single quote \', then reopen the next single quote.

    Breakdown diagram

    This diagram makes it clear by using brackets to show where the single quotes are opened and closed. Quotes are not "nested" like parentheses can be. You can also pay attention to the color highlighting, which is correctly applied. The quoted strings are maroon, whereas the \' is black.

    'urxvt -fg '\''#111111'\'' -bg '\''#111111'\'    # original
    [^^^^^^^^^^] ^[^^^^^^^] ^[^^^^^] ^[^^^^^^^] ^    # show open/close quotes
     urxvt -fg   ' #111111  '  -bg   ' #111111  '    # literal characters remaining
    

    (This is essentially the same answer as Adrian's, but I feel this explains it better. Also his answer has 2 superfluous single quotes at the end.)

提交回复
热议问题