0

I am writing a bash script. In a curl command I need a variable... It's just never recognized, or the command doesn't work. I searched the forum but didn't find anything suitable. Can you help me?

message="test"
curl -XPOST -d '{"msgtype":"m.text", "body":"$message"}' $curlurl

Since I need this json format, the double quotes must remain.

Thank you. Greetz Daniel

I have tried:

Substitute Single quote to double quote... \ to lose its meaning... but nothing work.

Cyrus
  • 84,225
  • 14
  • 89
  • 153
bash83376
  • 3
  • 1
  • https://stackoverflow.com/questions/22434290/jq-bash-make-json-array-from-variable – KamilCuk Nov 02 '22 at 19:35
  • In evaluating answers on the linked duplicates, the ones that use `jq --arg var "$var"` are categorically better (more reliable, more secure) than ones that don't. An answer that doesn't use jq will let a message's text exit the quotes it's contained in and insert extra fields into the message being posted, or simply be invalid and fail to be accepted by the server; using jq correctly will _always_ result in well-formed output. – Charles Duffy Nov 02 '22 at 19:42

1 Answers1

0

$message appears in a single-quoted string, so is not expanded. (The " are just parts of that single-quoted string, and have nothing to do with shell quoting.)

The "correct" version would be to double-quote the string and escape the embedded quotes:

curl -XPOST -d "{\"msgtype\":\"m.text\", \"body\":\"$message\"}' "$curlurl"

but this is both tedius and fragile, as you need to ensure any double quotes in the value of message are properly escaped. Much simpler is to let a tool like jq generate your JSON for you.

jq --arg m "$message" '{msgtype: "m.text", body: $m}' |
   curl -XPOST -d @-

@- tells the -d option to read from standard input.

chepner
  • 497,756
  • 71
  • 530
  • 681