Auto-reconnect your Bluetooth speaker on Ubuntu 24.04

changes not made as root:

nano ~/bt-reconnect.sh

#!/bin/bash

DEVICE_MAC=”<YOUR_DEVICE_MAC>”

while true; do
# Check if the device is connected
if !bluetoothctl info “$DEVICE_MAC” | grep -q “Connected: yes”; then
echo “Reconnecting to Bluetooth device…”
bluetoothctl connect “$DEVICE_MAC”
fi
sleep 10
done

chmod +x ~/bt-reconnect.sh

nano ~/.config/systemd/user/bt-reconnect.service

[Unit]
Description=Auto-reconnect Bluetooth speaker
After=bluetooth.service

[Service] ExecStart=/bin/bash /home/$USER/bt-reconnect.sh
Restart=always
User=%u

[Install]
WantedBy=default.target

systemctl –user daemon-reload
systemctl –user enable bt-reconnect.service
systemctl –user start bt-reconnect.service

echo ‘AutoEnable=true’ | sudo tee -a /etc/bluetooth/main.conf
sudo systemctl restart bluetooth