Skip to content

Instantly share code, notes, and snippets.

@fdob
Last active November 30, 2022 01:14
Show Gist options
  • Save fdob/5983637 to your computer and use it in GitHub Desktop.
Save fdob/5983637 to your computer and use it in GitHub Desktop.
in-diff: Use inotify to capture changes to a file, and output diffs to STDOUT. Needs inotify-tools.
#!/bin/bash
# hook into inotify to watch a file, and generate
# diffs for changes in real-time
#
# requires inotify-tools (apt-get install inotify-tools)
#
# @author Filipe Dobreira <[email protected]>
usage() {
echo "Usage:"
echo " in-diff <file>|help"
exit 1
}
# check arguments:
if [ "$1" == "" ] || [ ! -f "$1" ] || [ "$1" == "help" ]; then
usage
fi
# check dependencies:
command -v inotifywait >/dev/null 2>&1 || { echo >&2 "inotifywait(1) not available, please install inotify-tools"; exit 1; }
FILE="$1"
SNAP=$(tempfile)
# copy the initial snapshot to a temp file
cp "$FILE" "$SNAP"
watch () {
# start an inotifywatch loop:
while RES=$(inotifywait -q -e modify $FILE); do
diff "$FILE" "$SNAP" -d
cp "$FILE" "$SNAP"
done
}
# Keep watching for changes, even if the file is deleted.
while true; do
if [ ! -f "$FILE" ]; then
echo "" > "$SNAP"
else
watch
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment