Bashbashfile-watcherautomationdevelopmentproduction-ready

File Watcher with Debounce

A portable file watcher that detects changes and triggers commands with debouncing to prevent rapid-fire execution.


title: "File Watcher with Debounce" description: "A portable file watcher that detects changes and triggers commands with debouncing to prevent rapid-fire execution." category: "Bash" language: "bash" tags: ["bash", "file-watcher", "automation", "development", "production-ready"] createdAt: "2025-03-20" updatedAt: "2025-04-05"

Overview

A cross-platform file watcher that detects filesystem changes and runs a command with debouncing to prevent rapid-fire execution. Uses inotifywait on Linux, fswatch on macOS, with a polling fallback for other systems.

Code

# Watch src/ and run tests on change
./watch.sh ./src "npm test"
 
# Custom pattern and debounce
PATTERN="*.py" DEBOUNCE_MS=1000 ./watch.sh . "pytest"

Notes

  • inotifywait is the most efficient on Linux (kernel-level notification, zero CPU when idle)
  • fswatch is the macOS equivalent using FSEvents
  • The polling fallback works everywhere but uses more CPU and has higher latency
  • Debouncing prevents the command from running multiple times for batch saves (IDE save-all)
  • Exclude patterns prevent triggering on build artifacts, VCS metadata, and dependency directories