Exit bitcoind gracefully in a bash script 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:

#!/bin/bash

echo "Starting bitcoind in the background..."
bitcoind &amp;
sleep 5
echo "bitcoind started."
BITCOIND_PID=$!
echo $BITCOIND_PID

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

trap "cleanup" INT

# Run the script until we stop it
wait


This script produces the following output:

&lt;some bitcoind output&gt;
bitcoind started.
18574
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.