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>"}'

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.


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 :) .)

  • 3
    This works thanks! And in hindsight it makes sense
    – NelloDraws
    Mar 3 '19 at 7:38

Just to put one more solution here:

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

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


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

curl -s -X POST $URL -d@- <<EOF
        "id": 101,
        "text": "$variable"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.