在 Linux 中获取低电量警报的 Bash 脚本
我们将编写一个 bash 脚本,当电池的充电百分比低于某个指定的阈值时,它会显示“电池电量不足”。在开始之前,首先,我们需要了解一些基本的命令和术语,如下所述:
一些 Bash 命令:
- acpi :此命令返回电池充电的百分比,设备是充电还是放电以及电池完全放电之前的剩余时间。
- 示例: acpi -b产生以下输出:
Battery 0: Discharging, 13%, 00:52:52 remaining
- 此处,电池 0表示未充电,电池 1表示正在充电。 13%是电池已充电的百分比。 00:52:52是休眠前的剩余时间。
- notify-send:此命令用于提醒 Linux 中的通知弹出窗口。我们将使用此命令发出电池充电/放电警告的警报。
必需的包: espeak命令会说出或讲述您传递的任何参数,例如,如果您运行espeak “demo espeak”,它将说出“demo espeak” 。 Espeak 可以像任何普通软件包一样安装:
sudo apt install espeak
所需的 Linux 过滤器:
- grep : grep 过滤器用于在给定文件中搜索某些指定的字符串。
- cut : cut 过滤器允许我们在标准输出之前剪切和剥离文本文件的所需部分。
- sed :它代表流编辑器。此过滤器用于进行插入、删除、搜索和替换。我们在这里使用 sed 将“ % ”符号替换为“” 。
Python3
#!/bin/bash
# echo "Saurav Chaudhary Gujjar"
battery_level =$(acpi - b | grep - P - o '[0-9]+(?=%)')
# Battery 0: Discharging, 13%, 00:52:52 remaining
# To get the battery percentage only we'll cut the
# second value which ends at ", ". So we get 13%
# Now we'll replace the % sign by "", so 13% will
# be changed to 13 now.
# acpi -b produces output as
# echo $battery_level #$battery_level=13
# If the charger is plugged in, acpi shows "charging"
# and if it's not plugged in, it shows "discharging".
# if acpi -b shows charging, "grep -c" will return 1
# else it will return 0
ac_power =$(acpi - b | grep - c "Charging")
# echo $ac_power #1 if charging(plugged in) and 0 if discharging (not plugged in)
# checks if ac_power is ON and battery is full
battery_full =$(acpi - b | grep - c "Full")
# echo $battery_full
# when the battery is charging and it gets charged up to 100%
# echo $battery_level
# if charging and battery_level==100
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% "
# it notifies Battery is full and shows the battery
# full image which is stored in /usr/local/bin directory
# so, it will narrate, please remove the
# charger. It's charged up to 100%.
espeak "Saurav, Battrey is full, Please Remove the charger" - s 140
fi
# when the battery is not charging
# and it goes below 30%
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% "
# similarily, it narrates
#"please connect the charger"
espeak "Saurav, Battery is Low, Please connect the charger" - s 140
fi