温馨提示×

怎样编写ubuntu trigger脚本

小樊
45
2026-09-12 13:31:42
栏目: 智能运维

在 Ubuntu(以及其它 Linux 发行版)里,“trigger 脚本”并不是一个官方固定的术语,通常你指的是在某些事件发生时自动执行的脚本,比如:

  • systemd timer / path / service 触发
  • cron 定时触发
  • udev 设备插拔触发
  • inotify / watcher 文件变化触发
  • apt / dpkg trigger(软件包相关)

下面按最常见场景给你讲清楚怎么写。


一、用 systemd 写“触发脚本”(最推荐)

1️⃣ 定时触发(类似 cron)

场景:每 5 分钟执行一次脚本

脚本

# /usr/local/bin/my_trigger.sh
#!/bin/bash
echo "$(date) triggered" >> /var/log/my_trigger.log
chmod +x /usr/local/bin/my_trigger.sh

service

# /etc/systemd/system/my-trigger.service
[Unit]
Description=My Trigger Script

[Service]
Type=oneshot
ExecStart=/usr/local/bin/my_trigger.sh

timer

# /etc/systemd/system/my-trigger.timer
[Unit]
Description=Run My Trigger Every 5 Min

[Timer]
OnBootSec=1min
OnUnitActiveSec=5min

[Install]
WantedBy=timers.target

启用:

systemctl enable --now my-trigger.timer

查看:

systemctl list-timers

2️⃣ 文件/目录变化触发(path 触发)

场景:某个文件被修改就执行脚本

# /etc/systemd/system/my-path.path
[Unit]
Description=Watch Config File

[Path]
PathChanged=/etc/myapp.conf
Unit=my-trigger.service

[Install]
WantedBy=multi-user.target
systemctl enable --now my-path.path

二、用 cron 写定时 trigger(最简单)

crontab -e
*/5 * * * * /usr/local/bin/my_trigger.sh

适合:

  • 简单任务
  • 不需要复杂依赖

三、用 udev 写“设备触发脚本”

场景:U 盘插入执行脚本

脚本

# /usr/local/bin/usb_trigger.sh
#!/bin/bash
echo "USB plugged" >> /var/log/usb.log
chmod +x /usr/local/bin/usb_trigger.sh

udev 规则

# /etc/udev/rules.d/99-usb.rules
ACTION=="add", SUBSYSTEM=="usb", RUN+="/usr/local/bin/usb_trigger.sh"
udevadm control --reload

四、用 inotify 写“文件变化触发”

apt install inotify-tools
inotifywait -m -e modify /etc/myapp.conf | while read; do
    /usr/local/bin/my_trigger.sh
done

适合:

  • 实时监控
  • 不适合服务器长期运行(建议配合 systemd)

五、apt / dpkg trigger(高级)

如果你是打包软件,可以用:

# triggers
interest /etc/myapp
# post-invoke

一般用户很少用到。


总结建议

需求 推荐方式
定时执行 systemd timer / cron
文件变化 systemd path
设备插拔 udev
实时监控 inotify + systemd
软件包 dpkg trigger

如果你能说清楚:

  • 什么事件触发
  • 触发后做什么
  • 是否服务器环境

我可以直接帮你写一个完整可运行的示例

0