BudiBadu Logo
Samplebadu

Bash by Example: Folder Change Watcher

Bash 5.0+

Monitoring a directory for changes using a polling loop to detect new files, modified files, or deletions, implementing basic file watching without inotify dependencies, using find command with timestamps for change detection, automating responses to file system events, and building simple file monitoring solutions.

Code

#!/bin/bash

WATCH_DIR="watch_me"
mkdir -p "$WATCH_DIR"

# Store the initial state
# ls -lR lists recursively with details (size, time)
last_state=$(ls -lR "$WATCH_DIR")

echo "Watching $WATCH_DIR for changes (Ctrl+C to stop)..."

while true; do
    sleep 2
    current_state=$(ls -lR "$WATCH_DIR")

    if [ "$last_state" != "$current_state" ]; then
        echo "Change detected at $(date +%H:%M:%S)!"
        
        # In a real scenario, you might trigger a build, 
        # restart a server, or sync files here.
        
        # Update state to avoid repeated alerts
        last_state="$current_state"
    fi
done

Explanation

Watching a folder for changes is a common requirement for development tools (like "hot reloading" web servers) and automated workflows (like processing files as soon as they are uploaded via FTP). While Linux provides the inotify kernel subsystem for event-driven monitoring, it requires installing extra tools like inotify-tools. A portable, pure-Bash alternative is Polling.

Polling involves periodically checking the state of the system to see if anything has changed. In this script, we take a "snapshot" of the directory listing using ls -lR (Recursive Long listing). This captures filenames, sizes, and modification timestamps. We store this snapshot in a variable.

Inside an infinite while loop, we sleep for a few seconds (to avoid eating up 100% CPU) and then take a new snapshot. We compare the new snapshot string against the old one. If they differ, we know something changed—a file was added, deleted, or modified—and we can trigger our action. While less efficient than inotify for massive directory trees, it is simple, robust, and works on every Unix-like system out of the box.

Code Breakdown

8
ls -lR provides a comprehensive textual representation of the directory tree. If a single byte changes in a file, its size or timestamp will change, altering this string.
13
sleep 2 defines the polling interval. A shorter interval makes the script more responsive but consumes more system resources. A longer interval saves CPU but delays reaction time.