Prevent bash from adding single quotes to variable output

后端 未结 2 2075
盖世英雄少女心
盖世英雄少女心 2020-12-06 20:18

Problem: I\'m writing a script that performs several HTTP requests with curl and I want to add the headers to a variable, CURL_HEADERS

相关标签:
2条回答
  • 2020-12-06 20:26

    A reasonably straightforward solution is to use a bash array to store the four arguments you will want to pass:

    CURL_HEADERS=(
                 '-H' "Authorization: Basic ${AUTH_KEY}"
                 '-H' 'Content-Type: application/json'
    )
    
    curl -s "${CURL_HEADERS[@]}" 'http://www.example.org' > /dev/null
    

    Unlike scalar variables, which are just ordinary strings of ordinary characters no matter how many quotes they might contain, arrays are lists of strings, each one distinguished from each other one. In this sense, bash is just like almost every other programming language.

    This problem, and the solution I suggest as well as several other ones, is well-described in the Bash FAQ entry 50 (I'm trying to put a command in a variable, but the complex cases always fail!), which is worth reading in detail. (Link taken from a comment by @John1024.)

    0 讨论(0)
  • 2020-12-06 20:26

    The proposed array is a good design approach, but curl still adds single quotes to the array items that already contain double quotes around them, thus making invalid headers.

    0 讨论(0)
提交回复
热议问题