bash 使用来自 shell 变量的 JSON 内容运行 curl 命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49671580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 16:53:17  来源:igfitidea点击:

Running curl command with JSON content from a shell variable

linuxbashshell

提问by Borsn

I have the script below...

我有下面的脚本...

And I cannot seem to get the variables to work

而且我似乎无法让变量起作用

#!/bin/bash

info = 'Help...?'    
object='{"attachments": [{"title": "ti1","text": $info }]}'    
curl -X POST -H 'Content-type: application/json' --data '$object' https://hooks.slack.com/services/xxxx

exit 0

Even --data '$object'doesn't work without $info...as Slack API couldn't read my request.

即使--data '$object'没有$info……也无法工作,因为 Slack API 无法读取我的请求。

How do I fix this?

我该如何解决?

回答by Inian

Use double-quotes when passing shell variables and remove extra spaces in variable assignments.

传递 shell 变量时使用双引号并删除变量赋值中的额外空格。

curl -X POST -H 'Content-type: application/json' --data "$object"
#                                                       ^^^^^^^^^^

Use nested quotes to preserve the value inside JSON syntax

使用嵌套引号保留 JSON 语法中的值

info='Help...?'
object='{"attachments": [{"title": "ti1","text": "'"$info"'" }]}'