Skip to content

Instantly share code, notes, and snippets.

@ADTC
Created December 7, 2024 07:22
Show Gist options
  • Save ADTC/0802eae7ff87110048a14632b9d5f807 to your computer and use it in GitHub Desktop.
Save ADTC/0802eae7ff87110048a14632b9d5f807 to your computer and use it in GitHub Desktop.
Apple MacBook macOS Critical Battery Warning at 5% or less (`/usr/local/bin/*`)
#!/bin/bash
# Initialize the last_battery_percentage
last_battery_percentage=-1
while true; do
# Get the current battery percentage
battery_percentage=$(pmset -g batt | grep -o '[0-9]\+%' | tr -d '%')
# Only display the dialog if the new battery percentage is 5% or less
if [[ $battery_percentage -le 5 ]]; then
# Only display the dialog if the computer is on battery power
power_source=$(pmset -g batt | grep -o 'discharging')
if [[ $power_source == "discharging" ]]; then
# Check if the battery percentage has changed
if [[ $last_battery_percentage -ne $battery_percentage ]]; then
# afplay /System/Library/Sounds/Glass.aiff > /dev/null 2>&1
osascript <<EOF > /dev/null 2>&1
beep
display alert "Battery Level: ${battery_percentage}%" message "Connect a charger soon!" as critical giving up after 60
EOF
# Update the last battery percentage
last_battery_percentage=$battery_percentage
fi
else
# Reset the last battery percentage (shows message again if unplugged)
last_battery_percentage=-1
fi
fi
# Sleep for 1 second before checking again
sleep 1
done
nohup battcritical &
nohup osascript -e 'tell application "Terminal" to quit' &
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment