简体   繁体   中英

how do I pass a bash variable to curl?

I'm having difficulty passing a bash variable to 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. What am I missing?

Variables aren't expanded in single-quoted strings ( ' ), only inside double-quoted strings ( " ) and heredoc are variables expanded.

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. 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. Dealing with JSON in shell scripts has not made many people happy ;-)

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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