簡體   English   中英

如何將bash變量傳遞給curl?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM