The idea is to run this via cron job at some interval and have the excess of funds transfered to cold wallet address. So, I thought it will be easier to open source it so I can give it to the community and have it reviewed at the same time by more eyes. It hasn't been tested yet. So, any issues you see?
#!/usr/bin/bash
BITCOINCLI="/set/path/to/bitcoin-cli"
MINIMUM_TO_KEEP=0.1
RECEIVERS_ADDRESS=xxxyyyyzzzbitcoinaddress
echo bitcoin-cli executable is: $BITCOINCLI
tempOutput=$(mktemp)
tempOutputErr=$(mktemp)
#echo "$tempOutput"
#echo "$tempOutputErr"
"$BITCOINCLI" getbalance > "$tempOutput" 2> "$tempOutputErr"
#echo "output file:"
#cat "$tempOutput"
#echo "Error file:"
#cat "$tempOutputErr"
outputsize=$(wc -c "$tempOutput" | cut -f 1 -d ' ')
if [ $outputsize -ge 1 ]; then
balance=$(cat ${tempOutput})
else
balance=XYZ
echo "Error: Could not connect to server. Or some other error while tring to find balance. "
rm "$tempOutput" "$tempOutputErr"
exit
fi
echo Balance is "$balance"
sendamount=$(echo " $balance $MINIMUM_TO_KEEP - p" | tr '\n\r' ' ' | dc )
#echo comp = "$comp" x
if [ "$sendamount" > 0 ]; then
echo "Balance is greater than the amount to be kept, which is $MINIMUM_TO_KEEP"
echo Sending "$sendamount" BTC to the address "$RECEIVERS_ADDRESS"
"$BITCOINCLI" sendtoaddress $RECEIVERS_ADDRESS $sendamount > "$tempOutput" 2> "$tempOutputErr"
outputsize=$(wc -c "$tempOutputErr" | cut -f 1 -d ' ')
if [ $outputsize -ge 1 ]; then
echo Error while executing sendtoaddress. Could not send the amount. The error is:
cat "$tempOutputErr"
fi
else
echo "Balance is less than $MINIMUM_TO_KEEP"
fi
rm "$tempOutput" "$tempOutputErr"