Skip to content

Instantly share code, notes, and snippets.

@blvz
Forked from thiagoghisi/bluetooth-restart.sh
Last active July 20, 2021 09:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blvz/da82c3f584d6b4bf0f8fd1bf55558db4 to your computer and use it in GitHub Desktop.
Save blvz/da82c3f584d6b4bf0f8fd1bf55558db4 to your computer and use it in GitHub Desktop.
Script for Mac OSX to Restart Bluetooth service & Reconnect all recently paired devices
#!/usr/bin/env zsh
max_tries=3
devices=()
devices_ids=()
echo 'restarting bluetooth service.'
blueutil -p 0 && sleep 1 && blueutil -p 1
echo 'waiting bluetooth service to be restored.'
until blueutil -p | grep 1 >/dev/null; do sleep 1; done
echo
echo 'searching for disconnected keyboard/mouse.'
blueutil --paired | grep -E 'not connected.+(keyboard|mouse)' | while read line; do
devices+=`echo $line | awk -F '["]' '{print $2}'`
devices_ids+=`echo $line | awk -F '[ ,]' '{print $2}'`
done
if [[ ${#devices} == 0 ]]; then
echo 'no devices found.'
exit 0
elif [[ ${#devices} == 1 ]]; then
echo '1 device found.'
else
echo "${#devices} devices found."
fi
echo
for idx in {1..$#devices}; do
device=$devices[$idx]
device_id=$devices_ids[$idx]
echo "connecting to \"$device\" ($device_id)"
for retry in {1..$max_tries}; do
if blueutil --connect $device_id; then
echo 'success.'
echo
break
fi
if [[ $retry < $max_tries ]]; then
echo 'retrying...'
sleep 1
fi
done
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment