在 Linux 中,“trigger 脚本”通常指在某个事件发生时自动执行的脚本,常见场景包括:
下面按最常见、最实用的方式给你讲。
/etc/systemd/system/mytask.service
[Unit]
Description=My Trigger Task
[Service]
Type=oneshot
ExecStart=/opt/scripts/mytask.sh
/etc/systemd/system/mytask.timer
[Unit]
Description=Run My Task Every Hour
[Timer]
OnCalendar=hourly
Persistent=true
[Install]
WantedBy=timers.target
systemctl enable --now mytask.timer
/etc/systemd/system/watch.conf.path
[Path]
PathChanged=/etc/myapp/config.conf
[Install]
WantedBy=multi-user.target
/etc/systemd/system/watch.conf.service
[Service]
Type=oneshot
ExecStart=/opt/scripts/reload.sh
启用:
systemctl enable --now watch.conf.path
yum install inotify-tools
# 或
apt install inotify-tools
/opt/scripts/watch.sh
#!/bin/bash
inotifywait -m -e modify,create /data |
while read path action file; do
/opt/scripts/process.sh "$file"
done
后台运行:
nohup /opt/scripts/watch.sh &
/etc/udev/rules.d/99-usb.rules
ACTION=="add", SUBSYSTEM=="usb", ATTR{idVendor}=="1234", RUN+="/opt/scripts/usb.sh"
重新加载:
udevadm control --reload
crontab -e
*/5 * * * * /opt/scripts/backup.sh
#!/bin/bash
set -e
LOG=/var/log/trigger.log
echo "$(date) trigger start" >> $LOG
# your command
赋予权限:
chmod +x script.sh
| 需求 | 推荐 |
|---|---|
| 定时执行 | systemd timer / cron |
| 文件变化 | systemd path / inotify |
| 硬件事件 | udev |
| 简单任务 | cron |
如果你能告诉我:
我可以帮你直接写一个可用脚本。