Skip to content

Instantly share code, notes, and snippets.

@rosswintle
Last active March 2, 2024 14:56
Show Gist options
  • Save rosswintle/616803deae9d5ee97f592b33d4d7a015 to your computer and use it in GitHub Desktop.
Save rosswintle/616803deae9d5ee97f592b33d4d7a015 to your computer and use it in GitHub Desktop.
File watcher shell script - for use with front-end polling script
#!/bin/bash
##
## This script watches for changes in the specified directories and runs the build
## script when changes are detected.
##
## It writes a .modified_time file to the root of the project. This contains the
## timestamp of the last modification time.
##
## This is intended to be used with a front-end script that polls for changes
## and reloads, such as:
##
## https://gist.github.com/rosswintle/ae6e47d52e4e5b06dfe197543be4c5eb
##
## If you use this, be sure to add the following to your .gitignore file:
##
## .modified_time
##
# Directories to monitor (modify as needed)
directories=(
"src"
)
modifiedFilename=".modified_time"
# Project-global modification time file - in the public directory for a browser to check
projectModifiedTimeFile="public/$modifiedFilename"
# Echo the current timestamp to the file if it doesn't exist
if [[ ! -f "$projectModifiedTimeFile" ]]; then
echo "$(date +%s)" > "$projectModifiedTimeFile"
fi
# Function to check for file changes in a directory
check_for_changes() {
local dir="$1"
local last_mtime=""
if [[ -f "${dir}/$modifiedFilename" ]]; then
last_mtime=$(cat "${dir}/$modifiedFilename")
else
# Create the file if it doesn't exist
touch "${dir}/$modifiedFilename"
fi
if [[ "$(uname)" == "Darwin" ]]; then
# MacOS
new_mtime=$(find "$dir" -type f -not -name "$modifiedFilename" -exec stat -f '%m' {} \; | sort -n | tail -1)
else
# Assume Linux
new_mtime=$(find "$dir" -type f -not -name "$modifiedFilename" -exec stat -c '%Y' {} \; | sort -n | tail -1)
fi
if [[ "$new_mtime" != "$last_mtime" ]]; then
# Files have changed, run the build script
echo "Files changed in $dir, running build.sh"
./build.sh
# Update last modification time
echo "$new_mtime" > "${dir}/$modifiedFilename"
# Also update the global modification time
echo "$new_mtime" > "$projectModifiedTimeFile"
fi
}
# Main loop
while true; do
for dir in "${directories[@]}"; do
check_for_changes "$dir"
done
sleep 1
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment