Issue
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.
Solution
$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.
Answered By - chepner Answer Checked By - Cary Denson (WPSolving Admin)