I'm writing a bash script for some Bitcoin / Lightning experiments. I want to start bitcoind in the background (and also LN instances, but they are not the focus of this question). I want the script to shutdown bitcoind gracefully and exit on Ctrl+C. This is my attempt to implement this:


echo "Starting bitcoind in the background..."
bitcoind &
sleep 5
echo "bitcoind started."

cleanup() {
    echo 'cleaning up'
    pkill $BITCOIND_PID

trap "cleanup" INT

# Run the script until we stop it

This script produces the following output:

<some bitcoind output>
bitcoind started.
2019-09-17T14:12:20Z Adding fixed seed nodes as DNS doesn't seem to be available.
^C2019-09-17T14:14:07Z tor: Thread interrupt
cleaning up
2019-09-17T14:14:07Z opencon thread exit
2019-09-17T14:14:07Z torcontrol thread exit
2019-09-17T14:14:07Z addcon thread exit
2019-09-17T14:14:07Z Shutdown: In progress...
2019-09-17T14:14:07Z net thread exit
sergei:~$ 2019-09-17T14:14:07Z msghand thread exit
2019-09-17T14:14:07Z scheduler thread interrupt
2019-09-17T14:14:07Z Dumped mempool: 2e-06s to copy, 0.004053s to dump
2019-09-17T14:14:07Z [default wallet] Releasing wallet
2019-09-17T14:14:07Z Shutdown: done

Then I have to press Ctrl+C once again to exit the script.

How do I make the script shutdown bitcoind first and then exit automatically?

Related: How to use Ctrl+C to kill all background processes started in a Bash script?, Best way to kill processes created by bash script?.


Is bitcoin-cli available? If so, bitcoin-cli stop instead of pkill $BITCOIND_PID.

My own preference is to add sleep 2 following a stop, as I've experienced issues immediately restarting the stopped daemon where it behaves like a child thread hasn't finished cleaning up before the parent exits. That may not be what's happening - I've not investigated that behaviour.

  • I replaced 'pkill $BITCOIND_PID` with bitcoin-cli stop; sleep 2. Now I have: ^C2019-09-18T09:23:50Z tor: Thread interrupt 2019-09-18T09:23:50Z Shutdown: In progress... cleaning up <...> error: Could not connect to the server <...> 2019-09-18T09:23:50Z Shutdown: done which probably means the stop signal is sent to bitcoind two times: "directly" and through my trap. So when bitcoin-cli is called, bitcoind is already stopped. How can I prevent bitcoind from exiting before I call bitcoin-cli stop? – Sergei Tikhomirov Sep 18 '19 at 9:25
  • I see the same behaviour here, with differences I attribute to testing on 0.13.2. It might not be the stop signal being sent twice - it could be an attempt to discern if the initial shutdown was successful. – Alistair Mann Sep 18 '19 at 12:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.