Skip to content

Instantly share code, notes, and snippets.

@thiagoghisi
Created July 7, 2019 23:56
Show Gist options
  • Save thiagoghisi/50c3ba835ea72cdb0318fb3306fd2c76 to your computer and use it in GitHub Desktop.
Save thiagoghisi/50c3ba835ea72cdb0318fb3306fd2c76 to your computer and use it in GitHub Desktop.
Script for Mac OSX to Restart Bluetooth service & Reconnect all recently paired devices
#!/bin/bash
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 "Searching for devices not connected..."
devices=($(blueutil --paired | grep "not connected" | awk -F '[ ,]' '{print $2}'))
echo "Found ${#devices[@]} recently paired devices not connected"
for device in ${devices[@]}; do
for retry in {1..5}; do
echo "Trying to connect to ${device} ..."
if blueutil --connect ${device}; then break; fi
echo "Failed to connect to ${device}"
sleep 1
done
done
@erhhung
Copy link

erhhung commented Jan 30, 2020

Here's another version adapted from above that selects only recently paired devices (within the last day), and also prints out the device name. Note that the script requires a recent version of blueutil that can output JSON.

#!/bin/bash

# Restart the Bluetooth stack on macOS
#
# Adapted from https://gist.github.com/thiagoghisi/50c3ba835ea72cdb0318fb3306fd2c76
# See discussion at https://gist.github.com/nicolasembleton/afc19940da26716f8e90

# ensure blueutil and jq are installed
for bin in blueutil jq; do
  if ! hash $bin 2> /dev/null; then
    echo >&2 "Please install \"$_\" first!"
    exit 1
  fi
done

echo 'Restarting the Bluetooth service...'
blueutil -p 0 && sleep 1 && blueutil -p 1

echo 'Waiting for service to be restored...'
until [[ `blueutil -p` == 1 ]]; do sleep 1; done

echo 'Searching for recently paired devices...'
_IFS=$IFS; IFS=$'\n'
# jq expression returns lines: <address> <name>
devices=($(blueutil --recent --format json | jq -r 'def daysAgo(days): (now | floor) - (days * 86400); daysAgo(1) as $recent | .[] | select((.recentAccessDate | sub("[-+]\\d{2}:\\d{2}$"; "Z") | fromdate) > $recent and .paired and (.connected | not)) | .address + " " + .name'))
echo "Found ${#devices[@]} paired device(s) not connected."

for dev in ${devices[@]}; do
  addr=$(echo "$dev" | colrm 18)
  name=$(echo "$dev" | colrm 1 18)
  for retry in {1..3}; do
    echo "Trying to connect to ${addr}: ${name}..."
    if blueutil --connect ${addr} 2> /dev/null; then break; fi
    [[ $retry == 3 ]] && echo "FAILED to connect to ${addr}: ${name}."
    sleep 1
  done
done

IFS=$_IFS

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment