How to pass quoted parameters to another program

前端 未结 2 1963
慢半拍i
慢半拍i 2021-01-24 18:05

In a bash script, I need to pass a parameter to another program. The parameter has spaces in so must be quoted. Everything works fine in this simple case 1:

/bin         


        
相关标签:
2条回答
  • 2021-01-24 18:13

    Use an array; this is why they were introduced.

    FOO="ghi"
    # Contains one element, but not the literal quotes
    DEFAULTS=(--param="abc def $FOO")
    # command gets 1 argument, the single element of the array
    /some/command "${DEFAULTS[@]}"
    
    # Two elements
    DEFAULTS=(--param="abc def $FOO" --other="foo bar")
    # command gets 2 arguments
    /some/command "${DEFAULTS[@]}"
    
    0 讨论(0)
  • 2021-01-24 18:17

    You are almost there. You just have to put the $DEFAULTS into double quotes so that bash doesn't do the word spliting.

    DEFAULTS='param="ac def ghi"'
    perl -le'print $ARGV[0]' "$DEFAULTS"
    

    Output:

    param="ac def ghi"
    
    0 讨论(0)
提交回复
热议问题