Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Run a command each time a file is modified. For example: validate an html file automatically each time it's saved.
#!/bin/sh
# sample usage:
# ontouchdo malformed.html 'clear; xmllint --noout --valid malformed.html 2>&1 | head -n20'
#
# Now fix some things in malformed.html and save. See the remaining errors in real time. Ctrl-c to quit.
[ ! -r "$1" ] && echo 'Nothing to watch.' && exit 1
[ ! -n "$2" ] && echo 'Nothing to do.' && exit 1
# BSD and linux stat have different options for getting modification time. For better portability we
# need to determine which stat options to use. Since BSD stat has no --version, the following hack
# will do the trick.
stat --version &> /dev/null && STAT_OPTS='c%Y' || STAT_OPTS='f%m'
while :; do
# Get the current modification time of the file we're watching.
a=$(stat -$STAT_OPTS "$1")
# If it's different from the previous modification time, save the new time and do our thing.
[ "$b" != "$a" ] && b="$a" && sh -c "$2"
# Take a nap for a second then repeat.
sleep 1
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment