Ubuntu inotify 版本控制实践
概念澄清
快速实现步骤
#!/usr/bin/env bash
set -euo pipefail
MONITOR_DIR="/path/to/your/project"
GIT_DIR="$MONITOR_DIR/.git"
BRANCH="main"
DEBOUNCE=5 # 秒
if ! command -v inotifywait >/dev/null 2>&1; then
echo "请先安装 inotify-tools"
exit 1
fi
if [ ! -d "$GIT_DIR" ]; then
echo "目录不是 Git 仓库:$MONITOR_DIR"
exit 1
fi
# 防抖:记录最近一次提交时间(按“文件+事件”去抖)
declare -A last_commit_time
inotifywait -m -r -e modify,attrib,close_write,move,create,delete \
--format '%w%f %e' "$MONITOR_DIR" | while IFS=' ' read -r file event; do
# 忽略 .git 目录
[[ "$file" == */.git/* ]] && continue
now=$(date +%s)
key="$file|$event"
last=${last_commit_time[$key]:-0}
if (( now - last < DEBOUNCE )); then
continue
fi
last_commit_time[$key]=$now
echo "[$(date '+%F %T')] $event: $file"
git add -A "$MONITOR_DIR"
git commit -m "Auto commit: $event on $file" || true
# 如配置了上游且需要自动推送,取消下一行注释
# git push origin "$BRANCH" || true
done
注意事项与优化
升级与版本核对