Skip to content

Instantly share code, notes, and snippets.

@mbierman
Last active July 7, 2023 21:41
Show Gist options
  • Save mbierman/891720f9de76460b73aea08373c0e212 to your computer and use it in GitHub Desktop.
Save mbierman/891720f9de76460b73aea08373c0e212 to your computer and use it in GitHub Desktop.
Checks battery level for Magic Mouse, Magic Trackpad and Magic Keyboard on macOS.
#!/bin/bash
# Script that checks the battery level of connected Magic Keyboard, Magic Trackpad, and Magic Mouse and displays a notification if it is below a threshold (default 15%).
# Optionally set threshold as a parameter. ex: ./check_kb_battery.sh 10
COMPARE=${1:-15}
check_battery_level() {
device_name=$1
battery_level=$2
if [ -z "$battery_level" ]; then
echo "No $device_name Found."
else
echo -e "\n$device_name Battery Level: $battery_level%"
if [ "$battery_level" -lt "$COMPARE" ]; then
osascript -e "display notification \"Battery Level at $battery_level%\" with title \"Battery Low\" subtitle \"$device_name\""
echo -e "⚠️ $device_name battery level is low!! Currently at $battery_level%\n\n"
else
echo -e "✅ $device_name is good."
fi
fi
}
# Check Magic Keyboard
KBNAME=$(ioreg -c AppleDeviceManagementHIDEventService -r -l | grep -i 'Magic Keyboard' | cut -d = -f2 | cut -d \" -f2)
KBNAME=${KBNAME:-Magic Keyboard}
KBBATTERY=$(ioreg -c AppleDeviceManagementHIDEventService -r -l | grep -i "$KBNAME" -A 20 | grep BatteryPercent | cut -d = -f2 | cut -d ' ' -f2)
check_battery_level "$KBNAME" "$KBBATTERY"
# Check Magic Trackpad
TPNAME=$(ioreg -c AppleDeviceManagementHIDEventService -r -l | grep -i 'Magic Trackpad' | cut -d = -f2 | cut -d \" -f2)
TPNAME=${TPNAME:-Magic Trackpad}
TPBATTERY=$(ioreg -c AppleDeviceManagementHIDEventService -r -l | grep -i "$TPNAME" -A 20 | grep BatteryPercent | cut -d = -f2 | cut -d ' ' -f2)
check_battery_level "$TPNAME" "$TPBATTERY"
# Check Magic Mouse
MNAME=$(ioreg -c AppleDeviceManagementHIDEventService -r -l | grep -i 'Magic Mouse' | cut -d = -f2 | cut -d \" -f2)
MNAME=${MNAME:-Magic Mouse}
MBATTERY=$(ioreg -c AppleDeviceManagementHIDEventService -r -l | grep -i "$MNAME" -A 20 | grep BatteryPercent | cut -d = -f2 | cut -d ' ' -f2)
check_battery_level "$MNAME" "$MBATTERY"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment