Skip to content

Instantly share code, notes, and snippets.

@wolever
Created Oct 24, 2018
Embed
What would you like to do?
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