Want to check your connected bluetooth device battery level on a mac? Here is one way: using xbar (I am aware there are a bunch of other xbar plugins to do something similar, but I’ve been using my own script before I ever used xbar).
I have an old Apple Wireless Keyboard and a Magic Trackpad. I can set the Bluetooth Control Center to Show in the Menu Bar
or check via System Settings > Bluetooth:
It’s possible to get the same information via the ioreg
command to show the properties of all I/O Kit connected devices with batteries:
ioreg -rkBatteryPercent
The -k
parameter will list the properties of devices which contain the key BatteryPercent
. Add
-n AppleBluetoothHIDKeyboard
to filter the output to just the keyboard, or -n AppleDeviceManagementHIDEventService
to filter just the trackpad, or -n BNBMouseDevice
for a mouse.
However, ioreg
dumps a lot of information, when all I really want to see are the Product and BatteryPercent value. With a little grep
, sed
and tr
magic (refer to my text manipulation cheat sheet), I can format and limit the output:
ioreg -rkBatteryPercent -nAppleBluetoothHIDKeyboard | grep -e Product..= -e BatteryPercent..= | tr -d '\n' | sed -E "s/.*Product..= \"([^\"]*)\".*Percent..= (.*)/\1=\2%/g"
ioreg -rkBatteryPercent -nAppleDeviceManagementHIDEventService | grep -e Product..= -e BatteryPercent..= | tr -d '\n' | sed -E "s/.*Product..= \"([^\"]*)\".*Percent..= (.*)/ \1=\2%/g"
echo
I chuck this whole thing into an alias
, concatenating the 3 lines with ;
, so that I can easily check via the Terminal. Edit the second line if you use a mouse instead of a trackpad by replacing -n AppleDeviceManagementHIDEventService
with -n BNBMouseDevice
.
However, for those who want a for a persistent visual indicator, enter xbar. Create a new script with the refresh interval desired, e.g. battery_level.10m.sh
to refresh the battery value every 10 minutes:
#!/bin/sh
# <xbar.title>Battery Level</xbar.title>
# <xbar.author>C.Y. Wong, myByways.com</xbar.author>
# <xbar.abouturl>https://mybyways.com/blog/bluetooth-keyboard-and-trackpad-battery-level</xbar.abouturl>
kbd=$(ioreg -rkBatteryPercent -nAppleBluetoothHIDKeyboard|grep -e Product..= -e BatteryPercent..=|tr -d \\n|sed -E "s/.*Product..= \"([^\"]*)\".*Percent..= (.*)/\2%/g")
tpd=$(ioreg -rkBatteryPercent -nAppleDeviceManagementHIDEventService|grep -e Product..= -e BatteryPercent..=|tr -d \\n|sed -E "s/.*Product..= \"([^\"]*)\".*Percent..= (.*)/\2%/g")
echo ⌨️$kbd🖱️$tpd
echo ---
echo Bluetooth preferences\|shell=open\|param1=/System/Library/PreferencePanes/Bluetooth.prefPane
Instead of the Product value, I hardcode keyboard and trackpad emoji icons: