Trouble with bash shell script, attempting to POST variable JSON data using cURL
我无法使用bashshell脚本,试图使用curl发布变量JSON数据。我在用Mac电脑跑步。我可以成功地发布静态数据,但我似乎不知道如何合并变量。
为了这些例子,我介绍了
此脚本成功运行:
1 2 | #!/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"
1 2 3 | #!/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)"——所以看起来我误用了$payload。
1 2 3 4 | #!/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> |
最后,我试图撤离整个指挥部。挂起来失败了,可能是我误用了逃犯。我试过很多不同的逃跑方法。
1 2 3 4 5 | #!/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 |
我发现这个问题有些帮助,我也读过这个卷发教程。这些处理静态数据,我想我只是缺少一些基本的bash脚本。提前感谢您的帮助。
您只需正确使用
1 2 3 4 | 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> |
或者:
1 2 3 4 | 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> |
将变量包装在