Skip to content

Instantly share code, notes, and snippets.

@joaopfsilva
Created September 4, 2025 07:23
Show Gist options
  • Select an option

  • Save joaopfsilva/2411806d906f3ec58437a84d034942af to your computer and use it in GitHub Desktop.

Select an option

Save joaopfsilva/2411806d906f3ec58437a84d034942af to your computer and use it in GitHub Desktop.
Apple magic keyboard automatic reconnect
#!/usr/bin/env bash
# Reconnect Magic Keyboard on this Mac
# Your keyboard's BT address (as given)
# Requirement: brew install blueutil
# Find your device Bluetooth addresses -> blueutil --paired (search for magic keyboard)
ADDRESS_RAW="<insert-address-here>"
# --- No edits needed below ---
command -v blueutil >/dev/null 2>&1 || {
echo "blueutil not found. Install with: brew install blueutil"
exit 1
}
ADDR="$(echo "$ADDRESS_RAW" | tr '[:lower:]' '[:upper:]')"
# Ensure Bluetooth is on
blueutil --power 1 >/dev/null
# Already connected?
if blueutil --is-connected "$ADDR" | grep -q 1; then
echo "Magic Keyboard ($ADDR) is already connected."
exit 0
fi
# Try to connect (with a few retries)
for i in {1..5}; do
echo "Connecting to Magic Keyboard $ADDR (try $i)…"
if blueutil --connect "$ADDR"; then
# Verify connection
if blueutil --is-connected "$ADDR" | grep -q 1; then
echo "Connected!"
exit 0
fi
fi
sleep 1.5
done
# Last resort: toggle Bluetooth to “unstick” and try again
echo "Toggling Bluetooth to unstick…"
blueutil --power 0; sleep 1; blueutil --power 1; sleep 1
if blueutil --connect "$ADDR" && blueutil --is-connected "$ADDR" | grep -q 1; then
echo "Connected after toggle!"
exit 0
else
echo "Could not connect. The keyboard may still be connected to the other Mac."
exit 2
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment