Linux监控文件变化最主流、轻量又可靠的方式是inotify,基于内核事件驱动,需先安装inotify-tools,再用inotifywait命令或pyinotify库实现监听与响应。

Linux 监控文件变化最主流、轻量又可靠的方式就是 inotify,它基于内核事件驱动,不轮询、低开销、响应快。核心是 inotify-tools 工具集(尤其是 inotifywait),配合 shell 脚本或 Python 就能快速落地。
装好 inotify-tools 是第一步
没安装就无法使用:
- Ubuntu/Debian:
sudo apt update && sudo apt install inotify-tools - CentOS/RHEL 8+:
sudo dnf install inotify-tools - CentOS/RHEL 7:
sudo yum install inotify-tools
装完运行 inotifywait --version 确认可用。
用 inotifywait 快速监听关键事件
它适合命令行调试和简单自动化,常用组合示例:
- 持续监控目录下所有改动(含子目录):
inotifywait -m -r -e modify,create,delete,attrib /path/to/dir - 只关心新建文件,输出完整路径:
inotifywait -m -e create --format '%w%f' /path/to/dir - 带时间戳的简洁日志:
inotifywait -m --timefmt '%Y-%m-%d %H:%M:%S' --format '%T %w%f %e' -e modify /tmp/test.conf
注意:-m 表示持续监听;-r 启用递归;-e 可指定多个事件,避免无意义的 access 或 open 干扰。
写个 shell 脚本自动响应变化
把监控和动作串起来,比如配置更新后自动 reload 服务:
#!/bin/bash CONFIG="/etc/nginx/nginx.conf" while inotifywait -e modify "$CONFIG" >/dev/null; do nginx -t && systemctl reload nginx done
更健壮的做法是用管道捕获事件流:
- 监控日志目录,有新文件就上传:
inotifywait -m -e create --format '%w%f' /var/log/myapp | while read file; do curl -X POST --data-binary "@$file" http://api.example.com/upload; done - 脚本记得加
chmod +x,后台运行可用nohup ./watch.sh &或 systemd 管理。
需要复杂逻辑?试试 Python 的 pyinotify
适合要过滤路径、多级判断、并发处理或集成进已有项目的情况:
- 先安装:
pip install pyinotify - 基础监听示例:
import pyinotify
class MyHandler(pyinotify.ProcessEvent):
def process_IN_MODIFY(self, event):
if event.pathname.endswith('.log'):
print(f"[LOG MODIFIED] {event.pathname}")
wm = pyinotify.WatchManager()
notifier = pyinotify.Notifier(wm, MyHandler())
wm.add_watch('/var/log', pyinotify.IN_MODIFY, rec=True)
notifier.loop()
支持递归、通配符匹配、事件去重、异步回调等,比纯 shell 更可控。
基本上就这些。inotify 不复杂但容易忽略细节——比如默认单用户最多监控 8192 个文件(/proc/sys/fs/inotify/max_user_watches),大目录要提前调高;再比如监控符号链接需确保目标有读权限。用对了,它就是 Linux 文件监控的“隐形守门员”。










