在 Ubuntu(以及一般的 Linux 系统)里,“trigger” 这个词可能对应几种不同场景。下面我按最常见的几种情况给你说明,你可以看看你指的是哪一种。
如果你说的是 “当某个事件发生时自动执行任务”,通常用 systemd 服务 + path / timer / socket 来实现。
例如:当 /data/input.txt 被修改时执行脚本。
步骤:
sudo vim /etc/systemd/system/my-trigger.service
内容:
[Unit]
Description=Run script on file change
[Service]
Type=oneshot
ExecStart=/usr/local/bin/my-script.sh
sudo vim /etc/systemd/system/my-trigger.path
内容:
[Unit]
Description=Watch input file
[Path]
PathChanged=/data/input.txt
[Install]
WantedBy=multi-user.target
sudo systemctl enable --now my-trigger.path
✅ 文件一变化,脚本自动执行
例如:每天 3 点执行
sudo vim /etc/systemd/system/my-timer.timer
[Unit]
Description=Daily trigger
[Timer]
OnCalendar=*-*-* 03:00:00
Persistent=true
[Install]
WantedBy=timers.target
sudo systemctl enable --now my-timer.timer
如果你说的是 Ubuntu 软件包安装后的 trigger(如 apt install 后自动执行):
在 Debian/Ubuntu 包中:
/var/lib/dpkg/info/xxx.triggers
例如:
interest /usr/share/icons
然后在 postinst 中处理:
if [ "$1" = "triggered" ]; then
update-icon-caches /usr/share/icons
fi
⚠️ 这个一般只在打包 Debian 软件时用到。
如果只是“定时触发”:
crontab -e
0 3 * * * /usr/local/bin/my-script.sh
例如:U 盘插入时触发
sudo vim /etc/udev/rules.d/99-usb.rules
ACTION=="add", SUBSYSTEM=="block", RUN+="/usr/local/bin/usb.sh"
sudo udevadm control --reload
你可以直接告诉我:
我可以给你完整可直接用的示例。