1

I am trying to curl via bash script but unable to pass the value of var1 in curl request and getting error upon execution ...

 #!/bin/bash
 var1="some test message"
 curl 'https://link' \
 -H 'Content-Type: application/json' \
 -d '
{"msgtype": "text", 
  "text": {
      "content": $var1
   }
}'

3 Answers 3

2

Use below script.

https://aaa.com' -H 'Content-Type: application/json' -d '{"msgtype": "text", "text": {      "content": '"'$var1'"'   }}'
Sign up to request clarification or add additional context in comments.

1 Comment

This produces invalid JSON that uses single quotes to quote the value of the content key. Using parameter expansion to create JSON is not in general safe anyway.
2

Your variable $var1 doesn't get expanded by the shell because it is inside single quote '.

You need to use double quote to let bash do the parameter expansion, and escape your json data:

#!/bin/bash
var1="some test message"
curl 'https://link' \
-H 'Content-Type: application/json' \
-d "
{
  \"msgtype\": \"text\", 
  \"text\": {
    \"content\": \"$var1\"
  }
}"

Or you can use inline document (without the escaping hell, but the command becomes awkward):

#!/bin/bash
var1="some test message"
curl 'https://link' \
-H 'Content-Type: application/json' \
-d "$(cat <<EOT
{
  "msgtype": "text", 
  "text": {
    "content": "$var1"
  }
}
EOT
)"

Comments

2

In general, don't use parameter expansion to define JSON dynamically like this. There is no guarantee that your template, combined with the contents of the variable, produces well-formed JSON. (This is for the same reasons you don't use string interpolation to create dynamic SQL queries.) Use a tool like jq instead.

curl 'https://link' ... \
  -d "$(jq --argjson x "$var" \
           -n '{msgtype: "text", text: {content: $x}}')"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.