深浅模式
监控文件夹,同步文件,并进行防抖
#tech/linux/inotifywait
bash
#!/bin/bash
WATCHED_DIR="/var/www/html/dav/note_repo/doc"
TARGET_DIR="/home/www/yvan-ui-doc/docs/doc"
YVAN_UI_DOC_DIR="/home/www/yvan-ui-doc"
LOCK_FD=200
LOCK_FILE="/tmp/yarn_docs_build.lock"
# 封装调用 yarn build 的函数,使用文件描述符 200 加锁
yarn_build() {
(
flock -n "$LOCK_FD" || { echo "Build is currently running or locked."; return 1; }
echo "Starting build ..."
# 运行 yarn build 命令
cd "$YVAN_UI_DOC_DIR" && yarn docs:build
echo "Build finished."
) {LOCK_FD}>"$LOCK_FILE"
}
# 防抖变量,防止连续的 inotifywait 事件触发多次构建
DEBOUNCE_SEC=2
last_event_time=0
# inotifywait 循环监控变化
inotifywait -m -r -e close_write --format '%T' --timefmt '%s' "$WATCHED_DIR" | while read event_time; do
current_time=$(date +%s)
# 如果距离上次事件的时间小于防抖设定,则不进行操作
if [ $((current_time - last_event_time)) -lt $DEBOUNCE_SEC ]; then
continue
fi
# 更新 last_event_time 为当前时间
last_event_time=$current_time
sleep 2
# 同步文件到目标目录
rsync -av --delete "${WATCHED_DIR}/" "${TARGET_DIR}/"
# 使用后台进程调用构建函数
yarn_build &
done