简体   繁体   English

如何将bash变量传递给curl?

[英]how do I pass a bash variable to curl?

I'm having difficulty passing a bash variable to curl. 我很难将bash变量传递给curl。 My script is as follows: 我的脚本如下:

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 isn't passing to the curl string. $now没有传递给curl字符串。 What am I missing? 我错过了什么?

Variables aren't expanded in single-quoted strings ( ' ), only inside double-quoted strings ( " ) and heredoc are variables expanded. 变量不会在单引号字符串( ' )中展开,只在双引号字符串( " )中扩展,而heredoc是扩展的变量。

In your case, swapping the single quotes for double quotes will mean that you'll have to backslash escape all the double quotes of your JSON string. 在您的情况下,交换双引号的单引号将意味着您必须反斜杠转义JSON字符串的所有双引号。 Fear not! 不要怕! You can concatenate strings too! 你也可以连接字符串! You don't need any special operator like + or . 您不需要任何特殊的运算符,如+. for that, just stop quoting and start a new quoted string: 为此,只需停止引用并启动一个新的引用字符串:

$ curl [..] '...json...'"$now"'..json..'

Full example: 完整示例:

$ 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"
}

Stuff like this looks rather ugly/unreadable in my opinion. 在我看来,这样的东西看起来相当丑陋/难以理解。 This is a good moment to consider using a shell script with the aforementioned heredoc, or switch to a more structured programming language such as Python. 这是考虑将shell脚本与上述heredoc一起使用,或者转换为更结构化的编程语言(如Python)的好时机。 Dealing with JSON in shell scripts has not made many people happy ;-) 在shell脚本中处理JSON并没有让很多人满意;-)

SOLVED: 解决了:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM