如何监控电池状况和弹出通知?

从本质上讲,我希望这个评论成为一个有效的答案。

我知道如何从如何使用终端检查电池状态中提取电池百分比? :

upower -i $(upower -e | grep BAT) | grep --color=never -E percentage|xargs|cut -d' ' -f2|sed s/%// 

以及如何弹出基本通知:

 notify-send "battery low" 

但是如何设置(bash?)脚本来永久监视输出并根据此伪代码发送通知:

if battery_status < 10%然后notify-send "battery low"并将我的系统置于暂停状态sudo pm-suspend

第一步:让所有用户都可以访问pm-suspend,不要求密码

sudo visudo并在文件的末尾添加这一行: yourusername ALL=NOPASSWD: /usr/sbin/pm-suspend

来源: 如何在没有密码的情况下运行特定的sudo命令?

第二步:创建batwatch.desktop文件:

这是将自动启动监视脚本的文件。 该文件必须存储在$HOME/.config/autostart/文件夹中。

 [Desktop Entry] Type=Application Exec=/home/serg/bin/batwatch.sh Hidden=false NoDisplay=false Name=Battery Monitor Script 

请注意,该脚本位于我的/home/serg/bin文件夹中。 你可以使用你喜欢的任何文件夹,但是为了标准/ usr / bin或/ home / username / bin会更加优先。

来源: 如何在启动时运行脚本

第三步:创建实际脚本,保存在与Exec = line相同的位置

这是实际的脚本。 注意,我在那里使用bash,但它也应该与korn shell一起使用。 我添加了一些注释,因此请阅读这些注释以了解脚本的function

 #!/bin/bash # Check if the battery is connected if [ -e /sys/class/power_supply/BAT1 ]; then # this line is for debugging mostly. Could be removed #notify-send --icon=info "STARTED MONITORING BATERY" zenity --warning --text "STARTED MONITORING BATERY" while true;do # Get the capacity CAPACITY=$( cat /sys/class/power_supply/BAT1/uevent | grep -i capacity | cut -d'=' -f2 ) case $CAPACITY in # do stuff when we hit 11 % mark [0-9]|11) # send warning and suspend only if battery is discharging # ie, no charger connected STATUS=$( cat /sys/class/power_supply/BAT1/uevent | grep -i status | cut -d'=' -f2 ) if [ $(echo $STATUS) == "Discharging" ]; then #notify-send --urgency=critical --icon=dialog-warning "LOW BATTERY! SUSPENDING IN 30 sec" zenity --warning --text "LOW BATTERY! SUSPENDING IN 30 sec" sleep 30 gnome-screensaver-command -l && sudo pm-suspend break fi ;; *) sleep 1 continue ;; esac done fi 

第四步:重启并测试脚本是否有效

为此,您可以将数字[0-9]|11)调整为您喜欢的任何值,例如65)暂停为65%。 只有在未连接电源(即不充电)时,您才会暂停。

如果你喜欢这个,请告诉我,如果它有效,请确保upvote并点击我答案左侧的灰色复选标记!

干杯!

我已经为我的Vaio制作了一个类似的脚本,以便在电池充满电时通知我。 我利用UPOWER为我提供了电池状态的更新,并从中提取了相关部分。 这是代码:

 #!/bin/bash while true;do STATE=$( upower -i /org/freedesktop/UPower/devices/battery_BAT0 | grep "state:" | cut -b 26- ) if [ $STATE = "fully-charged" ] then zenity --info --text "Battery Full!" break fi done