如何将 Bash 变量传递给 Curl?

3

我在将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字符串中。我错过了什么吗?


我对curl不熟悉。我想我没有理解。所以这应该是curl --data-binary '{"jsonrpc":"1.0","id":"curltext","method":"importprivkey","params":["5HpHagT65TZzG1PH3CSu63k8DbpvD8s5ip4nEB3kEsreUs6zno1","$now",false]}' -H 'content-type:text/plain;' http://chad:password@127.0.0.1:8332/。 - Chad Ayers
2个回答

1

单引号字符串(')中不会展开变量,只有双引号字符串(")和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"
}

我认为这样的东西看起来相当丑陋/难以阅读。现在是考虑使用具有上述heredoc的shell脚本,或切换到更结构化的编程语言(如Python)的好时机。在shell脚本中处理JSON并没有让很多人感到满意;-)


我复制了你的例子 curl --data-binary '{"jsonrpc":"1.0","id":"curltext","method":"importprivkey","params":["test",'"$now"',false]}' -H 'content-type:text/plain;' http://httpbin.org/post 到终端,它正常工作。我用你的代码替换了我的脚本中的这部分并更改了URL,但现在出现了解析错误。 - Chad Ayers
这可能是因为您没有在JSON @ChadAyers中引用“$now”值。我已经修复了示例,现在应该可以工作了。 - Martin Tournoij
好的,我明白我做错了什么。当我回显curl时,变量传递得很好。现在我遇到了一个全新的问题。出现错误{"result":null,"error":{"code":-32700,"message":"解析错误"},"id":null}。 - Chad Ayers
这似乎是与服务器端点有关的问题,而不是与此curl命令本身相关的问题@ChadAyers。 - Martin Tournoij

1
已解决:
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/

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接