Skip to content

Instantly share code, notes, and snippets.

@molotovbliss
Forked from mikesmullin/watch.sh
Last active June 8, 2023 15:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save molotovbliss/aee0792414a00757e587333c438b7e4b to your computer and use it in GitHub Desktop.
Save molotovbliss/aee0792414a00757e587333c438b7e4b to your computer and use it in GitHub Desktop.
watchdo: Linux bash script to monitor file modifications recursively & execute bash commands as changes occur
#!/usr/bin/env bash
# script: watchdo
# author: Mike Smullin <mike@smullindesign.com>
# modified: Jared Blalock <mb@molotovbliss.com>
# possible use for monitoring .less changes to compile to .css
# license: GPLv3
# description:
# watches the given path for changes
# and executes a given command when changes occur
# usage:
# watch <path> <cmd...>
#
path=$1
shift
cmd=$*
sha=0
echo -en "Generating checksum from $path ...\n\n"
update_sha() {
# NOTE: If checksum generation is slow try a smaller size directory.
sha=`ls -lR --time-style=full-iso $path | sha1sum`
#sha=`find $path -type f -exec stat -c '%y %s %n *' '{}' + | sha1sum`
}
update_sha
previous_sha=$sha
build() {
echo -en "Executing: $cmd ...\n\n"
$cmd -s
echo -en "Resuming watch: $path "
}
compare() {
update_sha
if [[ $sha != $previous_sha ]] ; then
echo -n " >> Change detected! << \n\n"
build
previous_sha=$sha
else
echo -n .
fi
}
#trap build SIGINT
#trap exit SIGQUIT
echo -en " Press Ctrl+C to exit.\n"
echo -en " ... watching \"$path\"."
while true; do
compare
sleep 1
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment