0

I run a blockchain node from BSC (Binance smart chain) and I'd like to implement a script that periodically (30s) check if blocks are increasing and if not it would then restart the systemd service.

That's what I've started:

#!/bin/bash 

bsc_height=$(curl http://localhost:8545 -X POST -H "Content-Type: application/json" -d '{ "jsonrpc": "2.0","id": 0,"method": "eth_blockNumber"}' | awk -F ":" '{ print $4}' | sed 's|["{},]||g')
bsc_height_decimal=$(echo $((bsc_height)))

With that I'm able to get the current block's high through the variable bsc_height_decimal, let's say the value of it is currently 13083806. How would a bash loop that checks it every 30s and perform systemctl restart bsc if the count doesn't increase over this period of time look like?

My idea is to then run this script as a systemd service, or maybe crontab? I'm trying to figure out the best way to do it, what you guys think?

2
  • 1
    It is never necessary (and probably never useful) to pipe awk output into sed. Nov 30, 2021 at 20:10
  • FYI systemd service makes exactly what I want.
    – Daniel
    Nov 30, 2021 at 23:44

1 Answer 1

0
#!/bin/bash

declare -r WAIT_SEC='30'

bsc_height_decimal=
bsc_height_decimal_old=

while true; do
        bsc_height=$(curl http://localhost:8545 -X POST -H "Content-Type: application/json" -d '{ "jsonrpc": "2.0","id": 0,"method": "eth_blockNumber"}' | awk -F ":" '{ print $4}' | sed 's|["{},]||g')
        bsc_height_decimal=$(echo $((bsc_height)))
        if [ -n "$bsc_height_decimal_old" ] && [ "$bsc_height_decimal_old" -eq "$bsc_height_decimal" ]; then
                systemctl restart bsc
        fi
        bsc_height_decimal_old="$bsc_height_decimal"
        sleep "$WAIT_SEC"
done

And

awk -F ":" '{ print $4}' | sed 's|["{},]||g'

can be replaced by

awk -F ":" '{ output=$4; gsub("[\"{},]","",output); print output;}'
3
  • 1
    The first arg to gsub() is a regexp, not a string. If you use regexp instead of string delimiters then you won't need to escape the double quote - gsub(/["{},]/,"",output). It doesn't hurt but you don't actually need the variable either, gsub(/["{},]/,"",$4); print $4
    – Ed Morton
    Nov 30, 2021 at 23:23
  • thank you very much guys
    – Daniel
    Nov 30, 2021 at 23:42
  • @Daniel If you are satisfied with this answer then you should accept it so that your question does not look unanswered any more. Dec 5, 2021 at 23:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .