Piping Bitcoin RPC Commands

If you want to get the block header of the latest block generated on the bitcoin blockchain using bitcoin-cli it’s a little tricky (and hard to say!). You need to first find the latest block number (height), then find the hash of that block and then get the header using the hash.

Since the getblockheader command expects a blockhash as a parameter I use pipes to feed the result of one command into the next.

The pipe runs the following commands in this order.

  • First get the chain height using getblockcount
  • Feed this result to getblockhash to get the hash
  • Feed this result to getblockheader
  • Result is the header of the latest block

The result is a one line command to get the latest block header!

$ bitcoin-cli getblockcount | xargs bitcoin-cli getblockhash | xargs bitcoin-cli getblockheader
{
  "hash": "00000000000000000001e372ae2d2bc91903bd065d79e126461cd2bf0bbe6b3d",
  "confirmations": 1,
  "height": 600417,
  "version": 545259520,
  "versionHex": "20800000",
  "merkleroot": "e58f963d486c0a626938851ba9bfb6e4886cabcf2302573f827ca86040f997a3",
  "time": 1571688192,
  "mediantime": 1571685251,
  "nonce": 1693673536,
  "bits": "1715a35c",
  "difficulty": 13008091666971.9,
  "chainwork": "000000000000000000000000000000000000000009756da038619f842bfff6b6",
  "nTx": 2577,
  "previousblockhash": "0000000000000000000dbd8aada824ee952e87ef763a862a8baaba844dba8af9"
}

Join the conversation

1 Comment

  1. Thanks for this! Note that `bitcoin-cli getbestblockhash` gives the same result as `bitcoin-cli getblockcount | xargs bitcoin-cli getblockhash`

Leave a comment

Leave a Reply to Chris Cancel reply

Your email address will not be published. Required fields are marked *