温馨提示×

如何编写linux trigger脚本

小樊
37
2026-10-20 05:35:29
栏目: 智能运维

在 Linux 中,“trigger 脚本”通常指在某个事件发生时自动执行的脚本,常见场景包括:

  • cron / systemd timer:定时触发
  • systemd service + path unit:文件/目录变化触发
  • udev rule:设备插拔触发
  • inotify / fcron / incron:文件系统事件触发
  • git hook / CI trigger:代码变更触发

下面按最常见、最实用的方式给你讲。


一、使用 systemd 实现 Trigger(推荐)

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

创建 service

/etc/systemd/system/mytask.service

[Unit]
Description=My Trigger Task

[Service]
Type=oneshot
ExecStart=/opt/scripts/mytask.sh

创建 timer

/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

2️⃣ 文件变化触发(path unit)

/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

二、使用 inotify 触发脚本(实时监听)

安装

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 &

三、使用 udev 触发(USB / 硬件)

/etc/udev/rules.d/99-usb.rules

ACTION=="add", SUBSYSTEM=="usb", ATTR{idVendor}=="1234", RUN+="/opt/scripts/usb.sh"

重新加载:

udevadm control --reload

四、cron 定时 trigger(最简单)

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

如果你能告诉我:

  • 触发条件是什么?(时间 / 文件 / 设备 / 网络)
  • 系统版本(CentOS / Ubuntu / Rocky)

我可以帮你直接写一个可用脚本。

0 踩