How to escape single quotes within single quoted strings

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

    Here is another solution. This function will take a single argument and appropriately quote it using the single-quote character, just as the voted answer above explains:

    single_quote() {
      local quoted="'"
      local i=0
      while [ $i -lt ${#1} ]; do
        local ch="${1:i:1}"
        if [[ "$ch" != "'" ]]; then
          quoted="$quoted$ch"
        else
          local single_quotes="'"
          local j=1
          while [ $j -lt ${#1} ] && [[ "${1:i+j:1}" == "'" ]]; do
            single_quotes="$single_quotes'"
            ((j++))
          done
          quoted="$quoted'\"$single_quotes\"'"
          ((i+=j-1))
        fi
        ((i++))
      done
      echo "$quoted'"
    }
    

    So, you can use it this way:

    single_quote "1 2 '3'"
    '1 2 '"'"'3'"'"''
    
    x="this text is quoted: 'hello'"
    eval "echo $(single_quote "$x")"
    this text is quoted: 'hello'
    

提交回复
热议问题