BASH

Monitor File Changes and Trigger a Command

Create a simple file watcher using `inotifywait` that automatically executes a specified command, like a build script or server restart, when files in a directory change.

#!/bin/bash

# Usage: ./watch_and_run.sh <directory_to_watch> <command_to_execute>
# Example: ./watch_and_run.sh ./src "npm run build"

DIR_TO_WATCH="$1"
COMMAND_TO_RUN="$2"

if [ -z "$DIR_TO_WATCH" ] || [ -z "$COMMAND_TO_RUN" ]; then
    echo "Usage: $0 <directory_to_watch> <command_to_execute>"
    echo "Example: $0 ./src 'npm run build'"
    exit 1
fi

if ! command -v inotifywait &> /dev/null; then
    echo "Error: inotifywait not found. Please install inotify-tools."
    echo "On Debian/Ubuntu: sudo apt-get install inotify-tools"
    echo "On Fedora/RHEL: sudo dnf install inotify-tools"
    exit 1
fi

echo "Monitoring changes in '$DIR_TO_WATCH' and executing '$COMMAND_TO_RUN'..."

while true; do
    inotifywait -r -e modify,create,delete,move "$DIR_TO_WATCH"
    if [ $? -eq 0 ]; then
        echo "Change detected. Running command..."
        eval "$COMMAND_TO_RUN"
    else
        echo "inotifywait failed or was interrupted."
        break
    fi
done
How it works: This script acts as a basic file watcher. It requires `inotify-tools` (Linux-specific) to monitor a specified directory for modifications, creations, deletions, or moves. When a change is detected, it executes a user-defined command. This is incredibly useful for automatically recompiling code, restarting a development server, or triggering any build process without manual intervention during development.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs