使用bash shell脚本时遇到问题,尝试使用cURL POST变量JSON数据

我遇到了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>

现在,我想介绍一个格式化的日期。 这个脚本发布成功,但“$ now”被直接发布:即“Build failed $ 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>

我试图用printf格式化JSON有效载荷。 日期字符串被正确替换。 然而,这个失败并出现错误:“请求正文不能被解析为有效的JSON:没有JSON对象可以被解码:第1行0(char 0)” - 所以它看起来像我滥用$有效载荷。

#!/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>

最后,我试图评估整个命令。 这挂失败,可能是我滥用逃生。 我尝试了很多变体的逃跑。

#!/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: application/json" --data '{"color":"red","message":"Build failed $now","message_format":"text"}' https://api.hipchat.com/v2/room/<room>/notification?auth_token=<token>)
eval $cmd

我发现这个问题有点帮助,我也读过这个cURL教程。 这些处理静态数据,我想我只是缺少一些基本的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>

或者可选地:

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>

'包装变量'将使bash直接处理它们,而使用"将使它们被变量的值所取代

链接地址: http://www.djcxy.com/p/8549.html

上一篇: Trouble with bash shell script, attempting to POST variable JSON data using cURL

下一篇: REST API in Laravel when validating the request