How to escape single quotes within single quoted strings

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

    This function:

    quote () 
    { 
        local quoted=${1//\'/\'\\\'\'};
        printf "'%s'" "$quoted"
    }
    

    allows quoting of ' inside '. Use as this:

    $ quote "urxvt -fg '#111111' -bg '#111111'"
    'urxvt -fg '\''#111111'\'' -bg '\''#111111'\'''
    

    If the line to quote gets more complex, like double quotes mixed with single quotes, it may become quite tricky to get the string to quote inside a variable. When such cases show up, write the exact line that you need to quote inside an script (similar to this).

    #!/bin/bash
    
    quote ()
    {
        local quoted=${1//\'/\'\\\'\'};
        printf "'%s'" "$quoted"
    }
    
    while read line; do
        quote "$line"
    done <<-\_lines_to_quote_
    urxvt -fg '#111111' -bg '#111111'
    Louis Theroux's LA Stories
    'single quote phrase' "double quote phrase"
    _lines_to_quote_
    

    Will output:

    'urxvt -fg '\''#111111'\'' -bg '\''#111111'\'''
    'Louis Theroux'\''s LA Stories'
    ''\''single quote phrase'\'' "double quote phrase"'
    

    All correctly quoted strings inside single quotes.

提交回复
热议问题