Bash Script to get Low Battery Alert in Linux
We are going to write a bash script that will speak “Battery Low” when the battery’s charging percentage will go below some specified threshold value. Before starting this, first, we need to understand some basic commands and terminology which are described below:
Some Bash Commands:
- acpi: This command returns the percentage of battery charged, whether the device is charging or discharging and the amount of time left before the battery fully discharges.
- Example: acpi -b produces the following output:
Battery 0: Discharging, 13%, 00:52:52 remaining
- Here, Battery 0 means it is not charging and Battery 1 means it is charging. 13% is the Percentage of Battery Charged. 00:52:52 is the time left before it Hibernates.
- notify-send: This command is used to alert the notification popups in Linux. We will have the alert of the battery charging/discharging warning with this command.
Required Package: espeak command speaks or narrates whatever parameter you pass with it e.g it will speak out “demo espeak” if you run espeak “demo espeak”. Espeak can be installed like any normal package:
sudo apt install espeak
Required Linux Filters:
- grep: The grep filter is used to search for some specified string in a given file.
- cut: The cut filter allows us to cut and strip the desired section of text file before the standard output.
- sed: It stands for stream editor. This filter is used to make insertion, deletion, search, and replacement. We are using sed here for replacing the “%” sign by “”.
Python3
battery_level = $(acpi - b | grep - P - o '[0-9]+(?=%)' )
ac_power = $(acpi - b | grep - c "Charging" )
battery_full = $(acpi - b | grep - c "Full" )
if [[$ac_power - eq 1 & & $battery_level - eq 100 ]] | | [$battery_full - eq 1 ]
then
export DISPLAY = : 0.0 & &
sudo - u saurav DISPLAY = : 0 DBUS_SESSION_BUS_ADDRESS = unix: path = / run / user / 1000 / bus notify - send - u critical "Saurav, Battery is full" "Level: $battery_level% "
espeak "Saurav, Battrey is full, Please Remove the charger" - s 140
fi
if [[$ac_power - eq 0 & & $battery_level - lt 30 ]]
then
export DISPLAY = : 0.0 & &
sudo - u saurav DISPLAY = : 0 DBUS_SESSION_BUS_ADDRESS = unix: path = / run / user / 1000 / bus notify - send - u critical "Saurav Gujjar, Battery is Low." "Level: $battery_level% "
espeak "Saurav, Battery is Low, Please connect the charger" - s 140
fi
|
Last Updated :
31 Jan, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...