Check the battery level of connected bluetooth from command line in MacOS
2 min readMar 26, 2022
such as Mouse and Keyboard
ioreg
ioreg -r -l -n AppleHSBluetoothDevice
to show all show I/O Kit registry.
There are lots of infonations. We can use egrep
to get what we would
egrep
ioreg -r -l -n AppleHSBluetoothDevice | egrep ‘“BatteryPercent” = |^ \| “Bluetooth Product Name” = ‘
filter the keywords BatteryPercent and Bluetooth Product Name
Result:
amazing. next, we can format the output which look more readable.
sed
using sed
to replace unuseful info
sed ‘s/”Bluetooth Product Name” = “Magic Mouse 2”/Mouse:/’sed ‘s/”Bluetooth Product Name” = “Magic Keyboard with Touch ID”/ \| Keyboard:/’
and
sed ‘s/”BatteryPercent” = //’
command:
ioreg -r -l -n AppleHSBluetoothDevice | egrep '"BatteryPercent" = |^ \| "Bluetooth Product Name" = '| sed 's/"Bluetooth Product Name" = "Magic Mouse 2"/Mouse:/' | sed 's/"Bluetooth Product Name" = "Magic Keyboard with Touch ID"/ \| Keyboard:/'| sed 's/"BatteryPercent" = //'
Result:
Remove the unnecessary char and new line
remove the |
char by sed 's/\|//g'
remove the new line and white space by using string//[$'\t\r\n\ ']
command:
BATTLVL=$(ioreg -r -l -n AppleHSBluetoothDevice | egrep '"BatteryPercent" = |^ \| "Bluetooth Product Name" = '| sed 's/"Bluetooth Product Name" = "Magic Mouse 2"/Mouse:/' | sed 's/"Bluetooth Product Name" = "Magic Keyboard with Touch ID"/ \| Keyboard:/'| sed 's/"BatteryPercent" = //' | sed "s/\|//g")
BATTRPT=${BATTLVL//[$'\t\r\n\ ']}
echo $BATTRPT
Result:
At last
let us make it formative by add the %
to the number tail
sed -r 's/[0-9]+/\ &\%\n/g'
BATTLVL=$(ioreg -r -l -n AppleHSBluetoothDevice | egrep '"BatteryPercent" = |^ \| "Bluetooth Product Name" = '| sed 's/"Bluetooth Product Name" = "Magic Mouse 2"/Mouse:/' | sed 's/"Bluetooth Product Name" = "Magic Keyboard with Touch ID"/ \| Keyboard:/'| sed 's/"BatteryPercent" = //' | sed "s/\|//g")
BATTRPT=${BATTLVL//[$'\t\r\n\ ']}
# NOTE \d is not supported
echo $BATTRPT | sed -r 's/[0-9]+/\ &\%\n/g'
Result: