MacBook – set audio alarm for when charger is disconnected

batterychargingmacbook pro

My macbook air is getting old, so the battery is rather unreliable. This means I have to keep it constantly charged, or my computer may shut down suddenly as the battery plummets. But the charger is also old, and so sometimes if i shift the computer around it disconnects suddenly without my knowledge. Is there a way to set an audio alarm for when the computer disconnects from the charger? The only solutions online i found are for when the battery gets low, which may not occur because the battery drops and raises its percentage without warning, or unavailable in singapore.

thanks

Best Answer

This can be done by using the pmset -g batt command. The first line of output from this command indicates your power source, e.g.:

Now drawing from 'AC Power'

Or

Now drawing from 'Battery Power'

A possible use for this might be to change various commands together in a batch file, e.g.:

pmset -g batt | head -n 1 | grep "Battery"

In the above example, you'll only get output when you're running on battery power. So, a reasonable approach might be to use a bash script running via launchd or as a hidden Login Item in your profile. Something like this would work a charm:

#!/bin/bash
while true; do
  if $(pmset -g batt | head -n 1 | grep -q "Battery"); then
      say "Running on battery";
      sleep 5;
  fi
sleep 5;
done