Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

shell

macos

Exactly as the title says -- I'm looking for a way, in OSX, to tell me if my laptop is currently plugged in so that I can start/pause CPU intensive tasks as necessary.

Better yet, a way to get notifications whenever there is a change to the plugged in state.

like image 526
Nobody Avatar asked Jan 21 '14 04:01

Nobody


People also ask

How do I know my MacBook is charging?

After you connect the charger, the indicator light glows green if your battery is fully charged. If your battery is charging or charging is on hold, the indicator light glows amber.

Why is my MacBook plugged in and not charging?

Check the power outlet If the power outlet works, connect your USB-C power adapter and try to charge your Mac. If your Mac still won't charge, shut down your Mac and close the display for 30 seconds, then open the display and try to charge your Mac again. If you're not using a Mac with Apple silicon, reset the SMC.

How do I change the power source on a Mac?

Use Battery System Preferences to set options that control your computer's power adapter and energy use. Note: Some of the options may not be available, depending on your Mac. To open these preferences, choose Apple menu > System Preferences, click Battery , then click Power Adapter.

Why does my Mac show its charging when it's not?

Go to System Preferences app → Energy Saver and try toggling Show battery status in menu bar checkbox shown at the bottom. Try cleaning the ports and see if that helps. You should also consider seeking assistance with Apple authorized service provider especially if its covered under warranty.


1 Answers

You could use pmset:

-g ps / batt displays status of batteries and UPSs.

Saying:

pmset -g ps

would tell you if the laptop is running on AC power or using battery power.

To translate into a condition, something like the following should work:

if [[ $(pmset -g ps | head -1) =~ "AC Power" ]]; then
  echo "power on!"
fi
like image 160
devnull Avatar answered Nov 15 '22 10:11

devnull