Udev运行休眠脚本

Udev运行休眠脚本

我有这个 udev 规则,当电池电量为 5% 或以下时启动脚本:

$ cat /etc/udev/rules.d/90-lowbat.rules:

SUBSYSTEM=="power_supply", ATTR{status}=="Discharging", ATTR{capacity}=="5", RUN+="/opt/bin/battery-low.sh" 
SUBSYSTEM=="power_supply", ATTR{status}=="Discharging", ATTR{capacity}=="4", RUN+="/opt/bin/battery-low.sh"
SUBSYSTEM=="power_supply", ATTR{status}=="Discharging", ATTR{capacity}=="3", RUN+="/opt/bin/battery-low.sh"
SUBSYSTEM=="power_supply", ATTR{status}=="Discharging", ATTR{capacity}=="2", RUN+="/opt/bin/battery-low.sh"
SUBSYSTEM=="power_supply", ATTR{status}=="Discharging", ATTR{capacity}=="1", RUN+="/opt/bin/battery-low.sh"
SUBSYSTEM=="power_supply", ATTR{status}=="Discharging", ATTR{capacity}=="0", RUN+="/opt/bin/battery-low.sh"

这是脚本:

$ cat /opt/bin/battery-low.sh:

#!/bin/bash
# Critical battery level (acpi reports it at 5%)
CRITICAL=5

battery_level=`acpi -b | grep -o [0-9]*% | sed s/%//`
if [ ! $battery_level ]
then
   exit
fi
if [ $battery_level -le $CRITICAL ]
then
   if acpi -a | grep 'off-line'
   then
      # First warning
      sudo -u andreas DISPLAY=":0.0" notify-send -u critical "GIMME POWER ... will shut down in 60 sec"
      sleep 60s
         if acpi -a | grep 'off-line'
         then
            # Second warning
            sudo -u andreas DISPLAY=":0.0" notify-send -u critical "... shutting down"
            sleep 2s
            # This is the path to systemctl in Debian
            /bin/systemctl hibernate
         fi
   fi
fi

当电量为 5% 或以下时,脚本将被执行,我会收到第一个警告。

但是脚本的最后部分没有执行。由于机器仍然未插电,我没有收到第二次警告,并且计算机也没有休眠。

脚本当然可能有很多问题,但有趣的是,如果我运行脚本sudo ./battery-low.sh(当电池电量为 5% 或以下并且机器已拔掉插头时),一切都会正常 - 我收到两个警告并且计算机休眠大约 62 秒后。

udev 启动脚本的方式是否与我手动启动脚本时不同?如果是的话,怎么会这样呢?

相关内容