How to substitute quoted, multi-word strings as arguments?

前端 未结 4 1795
一整个雨季
一整个雨季 2020-12-01 21:08

I\'m trying to substitute a string variable, containing multiple quoted words, as a parameter to a command.

Thus, given the following example script (Note the -x in

4条回答
  •  我在风中等你
    2020-12-01 21:51

    I don't think it is doing what you think it is doing.

    [~]$ myArg="\"hello\" \"world\""
    [~]$ echo "string is:" $myArg
    string is: "hello" "world"
    

    I see no extra quotes of any kind- echo gets three argument strings.

    [~]$ cargs(){ echo $#; }
    [~]$ cargs "string is:" $myArg
    3
    

    Bash will expand the variable first, so

    cargs "string is:" $myArg
    

    becomes (though without the literal backslashes- this is why string escaping is a PITA)

    cargs "string is:" "\"hello\"" "\"world\""
    

    And the args array is:

    0x00:string is:0
    0x0B:"hello"0
    0x13:"world"0
    0x1B:0
    

    Now, if you add the *, or glob path expansion in one of those, Bash will at this point expand it, unless you escape it, or use single quotes in your literal command.

    [~]$ cargs "string is:" $myArg *
    19
    [~]$ cargs "string is:" $myArg "\*"
    4
    [~]$ cargs "string is:" $myArg '*'
    4
    

提交回复
热议问题