我在使用bash shell脚本时遇到问题,尝试使用cURL POST可变JSON数据.我是从Mac上运行的.我可以成功发布静态数据,但我似乎无法弄清楚如何合并变量.
为了这些例子,我介绍了<room>和<token>.
此脚本成功运行:
#!/bin/bash
curl -X POST -H "Content-Type: application/json" --data '{ "color":"red", "message":"Build failed", "message_format":"text" }' https://api.hipchat.com/v2/room/<room>/notification?auth_token=<token>
Run Code Online (Sandbox Code Playgroud)
现在,我想介绍一个格式化的日期.这个脚本成功发布,但"$ now"按字面意思发布:即"Build now $ now"而不是"Build failed 10-28-2014"
#!/bin/bash
now=$(date +"%m-%d-%Y")
curl -X POST -H "Content-Type: application/json" --data '{ "color":"red", "message":"Build failed $now", "message_format":"text" }' https://api.hipchat.com/v2/room/<room>/notification?auth_token=<token>
Run Code Online (Sandbox Code Playgroud)
我尝试使用printf格式化JSON有效负载.日期字符串被正确替换.但是,这失败并出现错误:"请求正文无法解析为有效JSON:无法解码JSON对象:第1行第0列(字符0)" - 所以我似乎误用了$ payload.
#!/bin/bash
now=$(date +"%m-%d-%Y")
payload=$(printf "\'{\"color\":\"red\",\"message\":\"Build failed %s\",\"message_format\":\"text\"}\'" $now)
curl -X POST -H "Content-Type: application/json" --data $payload https://api.hipchat.com/v2/room/<room>/notification?auth_token=<token>
Run Code Online (Sandbox Code Playgroud)
最后,我试图评估整个命令.这会因为挂起而失败,可能是因为我在滥用逃脱.我尝试了许多逃避变种.
#!/bin/bash
now=$(date +"%m-%d-%Y")
payload=$(printf "\'{\"color\":\"red\",\"message\":\"Build failed %s\",\"message_format\":\"text\"}\'" $now)
cmd=$(curl -X POST -H \"Content-Type: …
Run Code Online (Sandbox Code Playgroud)