我有一个简单的脚本来监视笔记本计算机的电池电量。由于我不断收到(code=exited, status=1/FAILURE)
错误,因此我设置*。service文件的方式有什么问题。
batterylevel-warning.sh
权限设置为777。
#!/bin/bash
CRITICAL_PERCENTAGE=`cat /sys/class/power_supply/BAT0/capacity`
STATUS=`cat /sys/class/power_supply/BAT0/status`
ICON="/usr/share/icons/Paper/512x512/status/battery-low.png"
if [ $STATUS == "Discharging" ]; then
if [ $CRITICAL_PERCENTAGE -eq 20 ]; then
notify-send -u critical -t 2000 -i $ICON "You need to charge your battery now!!! It is at $CRITICAL_PERCENTAGE%!!!"
fi
fi
batterylevel.service
[Unit]
Description=Send alerts on low battery starting at 25%.
[Service]
Type=simple
ExecStart=/bin/bash /home/myhome/.scripts/batterylevel-warning.sh
[Install]
WantedBy=multi-user.target
实施
# Create sym link
sudo ln-s /home/myhome/.scripts/batterylevel.service /etc/systemd/system
# Enable and start
sudo systemctl enable batterylevel.service
sudo systemctl start batterylevel.service
问题:当电池电量达到25%时,我运行sudo systemctl status batterylevel.service
并得到:
● batterylevel.service - Send alerts on low battery starting at 25%. Designed for silverlance.
Loaded: loaded (/home/myhome/.scripts/batterylevel.service; enabled; vendor preset: disabled)
Active: failed (Result: exit-code) since Mon 2020-03-02 23:04:02 PST; 4s ago
Process: 5357 ExecStart=/bin/bash /home/myhome/.scripts/batterylevel-warning.sh (code=exited, status=1/FAILURE)
Main PID: 5357 (code=exited, status=1/FAILURE)
我也在其中某处运行了sudo systemctl daemon-reload
,但仍然没有成功。抱歉,很长的帖子。
所以这里有两个问题。
第一个问题是systemd
期望simple
服务永远运行。当前,当您运行systemctl start
然后终止时,脚本将只运行一次。很好,这样可以提供多种服务,但我认为这不是您想要的。尝试重新编码脚本以进行轮询:
while true; do
if [ $STATUS == "Discharging" ]; then
if [ $CRITICAL_PERCENTAGE -eq 20 ]; then
notify-send -u critical -t 2000 -i $ICON "You need to charge your battery now!!! It is at $CRITICAL_PERCENTAGE%!!!"
fi
fi
sleep 60
done
第二个问题是您脚本中的某些内容正在返回错误代码。显而易见的候选者是notify-send
命令。 notify-send
不太可能通过systemd
与您的桌面管理器联系,因此几乎可以肯定是问题所在。下面的Stack Exchange文章描述了一个类似的问题,有人使notify-send
在cron
下运行。您需要执行类似的操作才能使其在systemd
下运行。就是说,让systemd
直接与桌面管理器对话总是很棘手,因此最好使用其他方法。 https://unix.stackexchange.com/questions/111188/using-notify-send-with-cron