How to escape single quotes within single quoted strings

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

    in addition to @JasonWoof perfect answer i want to show how i solved related problem

    in my case encoding single quotes with '\'' will not always be sufficient, for example if a string must quoted with single quotes, but the total count of quotes results in odd amount

    #!/bin/bash
    
    # no closing quote
    string='alecxs\'solution'
    
    # this works for string
    string="alecxs'solution"
    string=alecxs\'solution
    string='alecxs'\''solution'
    

    let's assume string is a file name and we need to save quoted file names in a list (like stat -c%N ./* > list)

    echo "'$string'" > "$string"
    cat "$string"
    

    but processing this list will fail (depending on how many quotes the string does contain in total)

    while read file
      do
        ls -l "$file"
        eval ls -l "$file"
    done < "$string"
    

    workaround: encode quotes with string manipulation

    string="${string//$'\047'/\'\$\'\\\\047\'\'}"
    
    # result
    echo "$string"
    

    now it works because quotes are always balanced

    echo "'$string'" > list
    while read file
      do
        ls -l "$file"
        eval ls -l "$file"
    done < list
    

    Hope this helps when facing similar problem

提交回复
热议问题