How do I add a variable to this curl command?

15,961

Solution 1

Stop the single quoted string, follow with the variable expansion, posibly double quoted, and resume the single quoted string:

--data '{"text": "'"$variable"'"}'

($variable should still expand to something that together with the surroundings forms legal JSON, or else the other side probably won't be very happy :) .)

Solution 2

Just to put one more solution here:

curl -X POST -u "apikey:${apikey}"
--header "Content-Type: application/json"
--data "{\"text\": \"${variable}\"}"
"${url}"

Basically, " is a quote to handle the following string together, \" escapes the quote, and ${varname} is a variable.

Solution 3

I tend to use heredocs when building JSON for use with curl:

curl -s -X POST $URL -d@- <<EOF
[
    {
        "id": 101,
        "text": "$variable"
    }
]
EOF
Share:
15,961

Related videos on Youtube

NelloDraws
Author by

NelloDraws

Updated on September 18, 2022

Comments

  • NelloDraws
    NelloDraws over 1 year

    I have a curl command that sends a string of text to the server and I've been trying to figure out how to either have the string of text come from a file or from a bash variable. The command looks like this:

    curl -X POST -u "apikey:<apikey>"
    --header "Content-Type: application/json"
    --data '{"text": "<variable>"}'
    "<url>"
    

    I can't figure out how to get a variable in there. I've tried replacing with $variable and $(< file) but I don't know how to get those to spit out text without an echo and I can't echo in a curl.

  • NelloDraws
    NelloDraws about 5 years
    This works thanks! And in hindsight it makes sense