在 Debian 中使用 inotify 提升效率的实用指南
一 核心概念与适用场景
二 快速上手与高效用法
sudo apt update && sudo apt install inotify-toolsinotifywait -m -r -e create,modify,delete --format '%w%f %e' /pathinotifywatch -r -e create,modify,delete /pathinotifywait -m -r -e create,delete,move /dir1 /dir2 /file1inotifywait -m -r -e create,delete,move /path -- /path/to/script.sh三 内核参数与系统资源优化
sudo sysctl -p 生效)
fs.inotify.max_user_watches=524288:提高单用户可监视的路径数量上限fs.inotify.max_user_instances=1024:提高单用户可创建的 inotify 实例数fs.inotify.max_queued_events=1048576:增大事件队列,减少高并发时的丢事件风险四 实战脚本与自动化
#!/usr/bin/env bash
set -uo pipefail
SOURCE_DIR="/path/to/source"
DEST_DIR="/path/to/dest"
inotifywait -m -r -e create,modify,delete,move --format '%w%f %e' "$SOURCE_DIR" | while IFS= read -r line; do
read -r FILE EVENT <<< "$line"
REL="${FILE#$SOURCE_DIR/}"
DEST="$DEST_DIR/$REL"
case "$EVENT" in
CREATE,ISDIR|MOVED_TO,ISDIR)
mkdir -p "$DEST"
;;
CREATE|MOVED_TO)
mkdir -p "$(dirname "$DEST")"
cp -a "$FILE" "$DEST"
;;
MODIFY)
rsync -a --inplace "$FILE" "$DEST"
;;
DELETE|MOVED_FROM)
rm -rf "$DEST"
;;
DELETE_SELF|MOVED_SELF)
rm -rf "$DEST"
;;
esac
done
nohup ~/monitor.sh &/etc/systemd/system/monitor.service):[Unit]
Description=Filesystem Monitor
After=network.target
[Service]
ExecStart=/home/youruser/monitor.sh
Restart=always
User=youruser
Group=youruser
Environment=PATH=/usr/bin:/bin
[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload && sudo systemctl enable --now monitor。五 性能与稳定性建议