在 Ubuntu 中,“触发规则”通常指的是 在特定事件发生时自动执行某个动作。不同场景下实现方式不同,下面按最常见的几种需求给你一个清晰对照,并给出可操作的示例。
适合:定时执行脚本、命令
crontab -e
| 需求 | 规则 |
|---|---|
| 每分钟 | * * * * * /path/to/script.sh |
| 每天 2 点 | 0 2 * * * /path/to/script.sh |
| 每小时 | 0 * * * * /path/to/script.sh |
| 开机后 1 分钟 | @reboot sleep 60 && /path/to/script.sh |
✅ 脚本需有执行权限:
chmod +x /path/to/script.sh
适合:服务启动、文件变化、设备插入、定时任务
# ~/.config/systemd/user/mytask.service
[Unit]
Description=My Task
[Service]
ExecStart=/path/to/script.sh
# ~/.config/systemd/user/mytask.timer
[Unit]
Description=Run my task
[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
[Install]
WantedBy=timers.target
systemctl --user daemon-reload
systemctl --user enable --now mytask.timer
适合:目录变化自动执行
sudo apt install inotify-tools
示例:
inotifywait -m /data -e create -e modify |
while read path action file; do
echo "$file changed"
done
~/.bashrc
~/.profile
⚠️ 不推荐放耗时任务
sudo nano /etc/NetworkManager/dispatcher.d/99-my-script
#!/bin/bash
if [ "$2" = "up" ]; then
/path/to/script.sh
fi
sudo chmod +x /etc/NetworkManager/dispatcher.d/99-my-script
适合:U 盘插入、串口连接
sudo nano /etc/udev/rules.d/99-usb.rules
ACTION=="add", SUBSYSTEM=="usb", RUN+="/path/to/script.sh"
重载规则:
sudo udevadm control --reload
~/.config/autostart/myapp.desktop
[Desktop Entry]
Type=Application
Exec=/path/to/script.sh
Hidden=false
| 场景 | 推荐方式 |
|---|---|
| 定时执行 | cron / systemd timer |
| 开机执行 | systemd / crontab @reboot |
| 文件变化 | inotify |
| 网络变化 | NetworkManager dispatcher |
| 设备插入 | udev |
| 登录执行 | .bashrc / autostart |
你可以直接告诉我:
我可以给你 完整可直接用的规则文件。