linux中可用inotifywait监听文件系统事件并自动触发rsync备份,需安装inotify-tools、编写带日志和目录创建的循环脚本,推荐以systemd服务长期运行,并可添加防抖或批量处理优化。

Linux 中可以通过 inotify 实时监控文件系统事件,并在检测到变化时自动触发备份任务。核心在于用 inotifywait(来自 inotify-tools)监听目录,结合 shell 脚本完成轻量、响应及时的事件驱动备份。
安装与基础监听
确保系统已安装 inotify-tools:
- Ubuntu/Debian:
sudo apt install inotify-tools - CentOS/RHEL:
sudo yum install inotify-tools或sudo dnf install inotify-tools
测试监听一个目录(如 /data)的创建、修改、删除事件:
inotifywait -m -e create,modify,delete,move_self /data
-m 表示持续监听,-e 指定关注的事件类型。输出会实时显示事件详情,可用于验证路径和权限是否正常。
编写可触发备份的监听脚本
将 inotifywait 与 while 循环结合,捕获事件后执行备份逻辑(如 rsync 同步):
#!/bin/bash MONITOR_DIR="/data" BACKUP_DIR="/backup/$(date +%Y%m%d)" LOG_FILE="/var/log/inotify-backup.log" <p>mkdir -p "$BACKUP_DIR"</p><div class="aritcle_card flexRow artxards"> <div class="artcardd flexRow"> <a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill4570" title="linux-performance-analyzer"><img src="https://img.php.cn/upload/skill/000/000/081/179013069298656.jpg" alt="linux-performance-analyzer" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a> <div class="aritcle_card_info flexColumn"> <a rel="nofollow" href="/xiazai/skill4570" title="linux-performance-analyzer" class="overflowclass">linux-performance-analyzer</a> <p class="overflowclass">Linux 性能分析与调优专家,覆盖 CPU、内存、磁盘 I/O、网络、内核参数、编译优化、容器/K8s。适用场景:系统卡顿/高负载、内存不足/OOM/Swap 高、CPU 异常/iowait 高。</p> </div> <a rel="nofollow" href="/xiazai/skill4570" title="linux-performance-analyzer" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a> </div> </div><p>while inotifywait -e create,modify,delete,move_self "$MONITOR_DIR"; do echo "[$(date)] Change detected, triggering backup..." >> "$LOG_FILE" rsync -a --delete "$MONITOR_DIR/" "$BACKUP_DIR/" >> "$LOG_FILE" 2>&1 done</p>
注意要点:
- 使用
rsync -a --delete保证备份一致性(归档模式 + 同步删除) - 避免在循环内重复创建
$BACKUP_DIR,建议提前生成或按需判断 - 添加日志记录便于排查失败原因
- 若需处理高频率写入(如日志轮转),可加
--exclude过滤临时文件或使用--throttle类机制防抖(需自行实现简易去重或延时)
作为服务长期运行
为保障稳定性,推荐将脚本注册为 systemd 服务:
# /etc/systemd/system/inotify-backup.service [Unit] Description=Inotify-triggered backup service After=network.target <p>[Service] Type=simple User=backupuser WorkingDirectory=/opt/scripts ExecStart=/opt/scripts/backup-watch.sh Restart=always RestartSec=10 StandardOutput=journal StandardError=journal</p><p>[Install] WantedBy=multi-user.target</p>
启用并启动:
sudo systemctl daemon-reloadsudo systemctl enable inotify-backup.servicesudo systemctl start inotify-backup.service
用 systemctl status inotify-backup 查看运行状态和最近日志。
进阶:事件去重与批量处理
单次写入可能触发多个事件(如保存文件触发 modify + attrib),直接每次执行 rsync 效率低。可引入简单防抖:
- 用
inotifywait -q -t 1设置 1 秒超时,配合 while 循环等待“静默期” - 或改用
inotifywait -m -e ... | while read ...; do sleep 0.5; done加延迟合并 - 更可靠的方式是用
find ... -cmin -1扫描最近 1 分钟变更,再统一备份,适合对实时性要求不苛刻但写入频繁的场景
不复杂但容易忽略。










