[英]how do I pass a bash variable to curl?
我很难将bash变量传递给curl。 我的脚本如下:
now=$(date)
curl --data-binary '{"jsonrpc":"1.0","id":"curltext","method":"importprivkey","params":["test",$now,false]}' -H 'content-type:text/plain;' http://chad:password@127.0.0.1:8332/
$now
没有传递给curl字符串。 我错过了什么?
变量不会在单引号字符串( '
)中展开,只在双引号字符串( "
)中扩展,而heredoc是扩展的变量。
在您的情况下,交换双引号的单引号将意味着您必须反斜杠转义JSON字符串的所有双引号。 不要怕! 你也可以连接字符串! 您不需要任何特殊的运算符,如+
或.
为此,只需停止引用并启动一个新的引用字符串:
$ curl [..] '...json...'"$now"'..json..'
完整示例:
$ now=$(date)
$ curl \
--data-binary \
'{"jsonrpc":"1.0","id":"curltext","method":"importprivkey","params":["test","'"$now"'",false]}' \
-H 'content-type:text/plain;' \
http://httpbin.org/post
{
"args": {},
"data": "{\"jsonrpc\":\"1.0\",\"id\":\"curltext\",\"method\":\"importprivkey\",\"params\":[\"test\",\"Thu Aug 24 10:10:32 BST 2017\",false]}",
"files": {},
"form": {},
"headers": {
"Accept": "*/*",
"Connection": "close",
"Content-Length": "111",
"Content-Type": "text/plain;",
"Host": "httpbin.org",
"User-Agent": "curl/7.55.1"
},
"json": null,
"origin": "34.194.174.91",
"url": "http://httpbin.org/post"
}
在我看来,这样的东西看起来相当丑陋/难以理解。 这是考虑将shell脚本与上述heredoc一起使用,或者转换为更结构化的编程语言(如Python)的好时机。 在shell脚本中处理JSON并没有让很多人满意;-)
解决了:
now=$(date)
curl --data-binary '{"jsonrpc":"1.0","id":"curltext","method":"importprivkey","params":['"$var3"','"$now"',false]}' -H 'content-type:text/plain;' http://chad:password@127.0.0.1:8332/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.