How to escape single quotes within single quoted strings

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

    shell_escape () {
        printf '%s' "'${1//\'/\'\\\'\'}'"
    }
    

    Implementation explanation:

    • double quotes so we can easily output wrapping single quotes and use the ${...} syntax

    • bash's search and replace looks like: ${varname//search/replacement}

    • we're replacing ' with '\''

    • '\'' encodes a single ' like so:

      1. ' ends the single quoting

      2. \' encodes a ' (the backslash is needed because we're not inside quotes)

      3. ' starts up single quoting again

      4. bash automatically concatenates strings with no white space between

    • there's a \ before every \ and ' because that's the escaping rules for ${...//.../...} .

    string="That's "'#@$*&^`(@#'
    echo "original: $string"
    echo "encoded:  $(shell_escape "$string")"
    echo "expanded: $(bash -c "echo $(shell_escape "$string")")"
    

    P.S. Always encode to single quoted strings because they are way simpler than double quoted strings.

提交回复
热议问题