Skip to content

Instantly share code, notes, and snippets.

@wolever
Created October 24, 2018 18:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wolever/b01037bf7032afbb82699bd2d4d049a4 to your computer and use it in GitHub Desktop.
Save wolever/b01037bf7032afbb82699bd2d4d049a4 to your computer and use it in GitHub Desktop.
Watch a directory for changes and run a command when it does
#!/bin/bash
# STOP! Before going any further, think: are you going to regret the decision
# to write this script?
# Deciding to write this in bash was not one of my better decisions.
# -- https://twitter.com/alex_gaynor/status/369892494114164736
IFS="`printf "\n\t"`"
set -u
if [[ "$#" -lt 2 ]]; then
echo "USAGE: $0 DIR CMD [... ARGS]"
exit 1
fi
dir="$1"
shift
if [[ ! -e "$dir" ]]; then
echo "ERROR: $dir does not exist!"
exit 1
fi
while :; do
"${@}"
res="$?"
if [[ "$?" -ne 0 ]]; then
echo "Command exited with: $res"
fi
sleep 1
changed="$(fswatch -E --exclude '\.sw.$' -1 "$dir")"
res="$?"
echo "$changed"
if [[ "$res" -ne 0 || -z "$changed" ]]; then
exit 1
fi
echo "$changed"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment