How can I determine the battery level of my magic mouse from the command line?
I know how to get it through the menubar, but how can I get it via the command line?
Use ioreg
and search for battery using grep
- Check the battery level of connected bluetooth headphones from the command line?
Since ioreg
is really verbose - here is one command that cuts down to the names of bluetooth devices and all percentage of battery for each.
ioreg -l |egrep "BatteryPercent|Bluetooth Product Name"
Building on useful answer from bmike [Jul 30 '17] ... with a way to further cut down the repetitions of device names: add (a) symbol carat (^) to signify start-of-line, and (b) escaped vertical bar preceded and followed by specific number of spaces:
ioreg -r -l -n AppleHSBluetoothDevice | egrep '"BatteryPercent" = |^ \| "Bluetooth Product Name" = '
Those filters yielded this result:
| "Bluetooth Product Name" = "Magic Keyboard with Numeric Keypad"
| | "BatteryPercent" = 59
| "Bluetooth Product Name" = "Magic Mouse 2"
| | "BatteryPercent" = 98
More filtering with sed and echoing the variable gave the result that I was looking for
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 Numeric Keypad"/ \| Keyboard:/'| sed 's/ | | "BatteryPercent" = / /'); echo $BATTLVL
The result in console:
| Mouse: 96 | Keyboard: 71
But, when I went to put it all into a bash script file, I found that while BATTLVL indeed contains only the desired words and phrases to be reported, it also contains newline characters -- but, they do not appear when the ECHO command is appended to the preceding command with a semicolon.
So, in order to make further use of the report results, we remove the newlines using techniques suggested in this post:
BATTRPT=${BATTLVL//[$'\t\r\n']}; # Strips all instances of tab, newline, return.
Finally, to add an OS X notification of mouse and keyboard battery level from the bash script, found it necessary to first build the script string into a variable, and then pipe it to osascript so that the double quotes would be included in the string.
theScript=$"display notification \"$BATTRPT\" "
echo $theScript | osascript