4

I'm trying to automate desktop setup, and as part of that I'd like to install a battery monitor package only if the machine currently has a battery attached (UPSes and other external batteries are not relevant). How can I go about detecting this?

My laptop has a directory /sys/class/power_supply/BAT1 and my desktop has nothing in the /sys/class/power_supply directory. Is that a rock-solid indicator on a system with sysfs? The reference doesn't mention BATn directories; are they likely a vendor-specific feature?

4

The presence of battery information in /sys/class/power_supply is a reliable indicator that the system supports a battery, and it's a standard Linux feature, but it won't always be called the same thing. Yours is called BAT1. I am looking at one here that is called battery. Also, not all entries in /sys/class/power_supply are batteries.

Look for all files matching the pattern /sys/class/power/supply/*/type. If at least one of them contains the work Battery, there is a battery. Other possible values for type are Mains and USB, maybe more.

One other thing that is possible is that the system accepts a battery but the battery has been physically removed. In that case, the Battery power supply will still show up. How you can detect this might be system-dependent, but try reading capacity or something and see if you get a read error, which probably indicates that the battery has been removed.

Details: Documentation/power/power_supply_class.txt

2
  • Could you reference a canonical document stating that /sys/class/power_supply is standard and will not suddenly change or a link to such a document? Jan 14 '15 at 21:39
  • 1
    @AlexejMagura Well, this is right from the source, I guess.
    – Celada
    Jan 15 '15 at 9:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.