3

I want to know which command should I use in my script to check the Battery if it's present or absent. like an if condition. thanks

When I try with following command I get error.

test@test-pc:~$ cat /proc/acpi/battery/BAT0/*
cat: /proc/acpi/battery/BAT0/*: No such file or directory

test@test-pc:~$ cat /sys/class/power_supply/BAT0/status
cat: /sys/class/power_supply/BAT0/status: No such file or directory

Also acpi is already installed.

I used dmesg | grep battery to check the battery and the result was this:

[    1.309638] ACPI: Deprecated procfs I/F for battery is loaded, please retry with CONFIG_ACPI_PROCFS_POWER cleared
[    1.309643] ACPI: Battery Slot [BAT1] (battery present)

The result of acpi -i is as following too:

Battery 0: Unknown, 79%
Battery 0: design capacity 8244 mAh, last full capacity 6591 mAh = 79%

And now how can I use this result in my script?

0

2 Answers 2

4

The file /sys/class/power_supply/BAT0/status may help you.

If the battery is present it's for example:

cat /sys/class/power_supply/BAT0/status
Charging

Another place could be:

cat /proc/acpi/battery/BAT0/*

Or to view ACPI related information use the command:

acpi -i

acpi -i produces no output to the standard output when no battery is present. In a script use it as follows:

if [ -z "$(acpi -i)" ]; then
  echo "battery not present"
else
  echo "battery present"
fi
1
  • 1
    -z checks if the length of STRING is zero.
    – chaos
    Sep 3, 2014 at 13:44
2

The python code below checks the output of acpi -i. if there is no output, "Where is my battery?" is printed, otherwise "OK, present". Of course you can put any command there, using either subprocess.call() or subprocess.Popen().

#!/usr/bin/env python

import subprocess

get_batterystatus = subprocess.check_output(['acpi', '-i']).decode('utf-8').strip()

if get_batterystatus == "":
    print "Where is my battery?" 
else:
    print "OK, present" 
3
  • 1
    This code is unnecessarily verbose (and slow). Why not get_batterystatus = lambda: subprocess.check_output(['acpi', '-i'], stderr=subprocess.DEVNULL).decode('utf-8').strip()?
    – phihag
    Sep 3, 2014 at 16:28
  • @phihag thanks for mentioning, I made some changes. That makes a difference, mainly in elegance; the timing is pretty much the same. Weird thing is that it is twice as fast in python2. left it in python2. Sep 3, 2014 at 20:21
  • @KasiyA I am afraid I don't understand what you mean? Do you mean the () around the message? I changed it to python2 where in print no () is used. Sep 4, 2014 at 13:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .