219 字
1 分钟
Linux笔电服务器配置低电量自动关机与电池保护

低电量关机#

文中使用的脚本为电池量低于40%进行关机,处于充电状态取消关机

部署脚本如下

Terminal window
nano /opt/batterydown.sh
nano /usr/lib/systemd/system/batterydown.service
systemctl daemon-reload
systemctl enable --now batterydown.service
systemctl status batterydown.service

sh文件:

#!/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
_shut=false
sleep 20
while :
do
# 获取电池电量
capacity=$(cat /sys/class/power_supply/BAT0/capacity)
# 获取电池状态
status=$(cat /sys/class/power_supply/BAT0/status)
echo "Battery Status: $status"
echo "Battery Capacity: $capacity%"
if [[ $capacity -lt 40 ]]; then
if [[ $status != "Full" && $status != "Charging" ]]; then
echo "Battery capacity is below 40%. Going down!"
if [ "$_shut" == "false" ]; then
echo "Going Down!!!!"
shutdown -h +10
fi
_shut=true
else
if $_shut; then
echo "Battery is Charging. Canceling shutdown!"
shutdown -c
_shut=false
fi
fi
else
if $_shut; then
echo "Battery capacity is above 40%. Canceling shutdown!"
shutdown -c
_shut=false
fi
fi
sleep 20
done

service文件:

Terminal window
[Unit]
Description=batterydown Service
[Service]
User=root
ExecStart=/bin/bash /opt/batterydown.sh
[Install]
WantedBy=default.target

电池保护#

先装一下相关的软件包

apt install tlp
nano /etc/tlp.conf
#找到下面两行进行取消注释和修改
START_CHARGE_THRESH_BAT0=50
STOP_CHARGE_THRESH_BAT0=80
systemctl restart tlp

状态查看#

tlb-stat -b
Linux笔电服务器配置低电量自动关机与电池保护
https://iiii.fun/posts/linux/linux-laptop-battery-server/
作者
慶靈
发布于
2025-03-08
许可协议
CC BY-NC-SA 4.0