Battery level warning for mac os x

Alec Jacobson

September 23, 2010

weblog/

My girlfriend's MacBook has an embarrassingly short battery life and has a habit of just shutting off without any warning. I wrote a little bash script to pop up a warning if her battery gets below a threshold. Here's the script, I save it in a file called ~/.battery_warning.sh:
#!/bin/bash
min_percentage="15"
percentage=`pmset -g batt | grep -o "[0-9]\+%; discharging" | \
  sed -e "s/%.*$//"`
if [ "$percentage" ]; then
  if [[ $percentage -lt $min_percentage ]] ; then
    osascript -e "tell application \"System Events\"
        activate
        display dialog \"Battery almost dead: $percentage%\" \
          with icon 0 with title \"Warning\" buttons {\"OK\"} \
          default button 1
      end tell"
  fi
fi
Then I set it up as a cron job to check every 5 mins:
*/5 * * * *  bash ~/.battery_warning.sh