Generating sh code from within sh: Escaping

后端 未结 2 1695
慢半拍i
慢半拍i 2021-01-22 22:04

I have a shell variable (we shall call x) containing a string with shell meta characters. For example, I might have

abc  \"def\'s\"  ghi
         


        
2条回答
  •  一向
    一向 (楼主)
    2021-01-22 22:42

    sh has functions.

    # quote() - Creates a shell literal
    # Usage:  printf '%s\n' "...$( quote "..." )..."
    quote() {
        printf \'
        printf %s "$1" | sed "s/'/'\\\\''/g"
        printf \'
    }
    

    Testing:

    $ x='abc  "def'\''s"  ghi'
    
    $ printf '%s\n' "$x"
    abc  "def's"  ghi
    
    $ printf '%s\n' "prog `quote "$x"`"
    prog 'abc  "def'\''s"  ghi'
    
    $ printf '%s\n' "prog $( quote "`pwd`" )"
    prog '/home/ikegami/foo bar'
    

    $ printf '%s\n' "$( quote "a'b" )"
    'a'\''b'
    
    $ printf '%s\n' "$( quote '-n' )"
    '-n'
    
    $ printf '%s\n' "$( quote '\\' )"
    '\\'
    
    $ printf '%s\n' "$( quote 'foo
    bar' )"
    'foo
    bar'
    

    A version that takes multiple arguments:

    # quote() - Creates a shell literal
    # Usage:  printf '%s\n' "$( quote "..." "..." "..." )"
    quote() {
        local prefix=''
        local p
        for p in "$@" ; do
            printf "$prefix"\'
            printf %s "$p" | sed "s/'/'\\\\''/g"
            printf \'
            prefix=' '
        done
    }
    

提交回复
热议问题