The problem#
For a compile-on-save workflow where some computation is done in response to every change to a file, if there may sometimes be many changes close together, it may be wasteful to respond to all of them. This is often handled by debouncing the events: instead of responding to every change, ignore changes that occur too close together in time.
The solution#
watch_todo_debounced.sh
is a modification
of the watch_todo.sh
script from my recent
post on converting todo.txt files to HTML. It uses a
script I found called debounce.sh to wait until there have been no
updates to the todo.txt file for 5 seconds before generating the HTML
file. The core logic looks like this:
while true
do
inotifywait -e close_write "$1" >/dev/null
echo "TODO file updated."
done | debounce.sh read $delay "./do-something.sh \"$1\""
$delay
is the delay in seconds to wait before taking an action. $1
is file to watch for changes on and ./do-something.sh
is the script to
run on it when it changes.