How to sense whether I'm on battery or not?

Hey Peter,

Sometimes searching the forum bears fruit.  :wink:

When searching for battery power the first hit is Trigger macro When On/Off Battery Power.

Searching the wiki for battery returns this result.

So – there's a Keyboard Maestro function that returns 0 or 1 for the battery in-use status.

You can also use the shell:

How do I programatically detect if my laptop is plugged in or not? (osx)

The basic command:

pmset -g ps

Run it in the Terminal to see what it does – the output looks like this:

Now drawing from 'AC Power'
 -InternalBattery-0 (id=4456547)	100%; charged; 0:00 remaining present: true

Here's how to use it as an effective test:

if [[ $(pmset -g ps | head -1) =~ "AC Power" ]]; then
  echo "Power On"
else
  echo "Power Off"
fi

-Chris

4 Likes