#!/bin/bash
# Get the battery percentage for battery 0
battery0_percent=$(cat /sys/class/power_supply/BAT0/capacity)
# Get the battery percentage for battery 1
battery1_percent=$(cat /sys/class/power_supply/BAT1/capacity)
# Threshold level
threshold=10
# Check if either battery is less than 10%
if [ "$battery0_percent" -lt "$threshold" ] || [ "$battery1_percent" -lt "$threshold" ]; then
# Display a Zenity warning
zenity --warning --text "Battery level is below 10% on one or both batteries!"
fi
当我的其中一个电池电量低于 10% 时,此脚本会发送警告。
我怎样才能在后台运行这个脚本,所以我会在需要时通知我。任何想法?
您有两种方法可以做到这一点:
在命令后面添加&符号
即使在关闭终端后,这也会通过在 shell 中生成子进程来保持命令运行
如果您希望在注销 shell 后仍保留某些内容,可以在命令前添加 nohup
这还将命令的输出重定向到名为“nohup.out”的文件中
如果您想更进一步并在启动时运行此脚本,您还有一些不同的选择:
如果您希望每次启动显示服务器时都启动此脚本:
使用 x11:
将这一行添加
./battery-script.sh &
到您的末尾,~/.xinitrc
以便每次启动 x11 时运行脚本(可能在这种情况下您想要什么,考虑到您有一行用于 zenity 警告)如果您运行 wayland,这取决于您的 wm ,对于 sway 来说是 .config/sway/config.d/autostart_applications
如果您想在显示服务器启动之前运行脚本,您可以将脚本放入
/etc/profile.d
正如已经说过的,您可以简单地使用
&
在后台运行。如果您需要分离/附加,最好的方法是使用tmux或screen,这样,您可以根据需要附加/分离会话。
要在后台运行命令
screen
:列出可用的会话:
重新附加:
创建一个 systemd 计时器单元,使其在后台定期运行。
/etc/systemd/system/my-batterywatcher.service
/etc/systemd/system/my-batterywatcher.timer
有几个建议在后台运行它或作为传统守护进程运行它,但这需要在活动用户的会话内部运行(因为它想要访问经过身份验证的用户的显示)。
不同的 X11 环境(更不用说 Wayland)有不同的启动每会话服务的方式,但我相信最可移植的应该是XDG 自动运行机制。即在 /etc/xdg/autostart/ 中添加(或链接)脚本