Last active
May 1, 2025 10:51
-
-
Save CuddlyBunion341/7e2a8248e62011c06919567e62e93713 to your computer and use it in GitHub Desktop.
Simple Directory watcher
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Function to watch a directory for changes on macOS and execute a command. | |
# Requires fswatch to be installed (e.g., via Homebrew: brew install fswatch). | |
# Usage: watch_dir <directory> <command> | |
# | |
# Arguments: | |
# <directory>: The directory to watch for changes. | |
# <command>: The command to execute when a change is detected. | |
function watch_dir { | |
if [ "$#" -lt 2 ]; then | |
echo "Usage: watch_dir <directory> <command>" | |
return 1 | |
fi | |
local directory="$1" | |
local command="$2" | |
if [ ! -d "$directory" ]; then | |
echo "Error: Directory '$directory' not found or is not a directory." | |
return 1 | |
fi | |
# Check if fswatch is installed | |
if ! command -v fswatch &> /dev/null | |
then | |
echo "Error: fswatch is not installed." | |
echo "Please install it, e.g., using Homebrew: brew install fswatch" | |
return 1 | |
fi | |
echo "Watching directory: '$directory' (macOS)" | |
echo "Executing command on change: '$command'" | |
echo "Press Ctrl+C to stop." | |
# Use fswatch to monitor the directory recursively for any events | |
# and execute the command on each event using xargs. | |
# -r: Monitor recursively | |
# -0: Use null character as delimiter (for safety with filenames containing spaces) | |
fswatch -r -0 "$directory" | | |
xargs -0 -n 1 -I {} bash -c "$command" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage: