Skip to content

Instantly share code, notes, and snippets.

@AVAtarMod
Forked from senko/onchange.sh
Last active August 19, 2021 06:59
Show Gist options
  • Save AVAtarMod/e8bb8ee64cdb009f68d2f70615632b62 to your computer and use it in GitHub Desktop.
Save AVAtarMod/e8bb8ee64cdb009f68d2f70615632b62 to your computer and use it in GitHub Desktop.
Watch entered directory and execute a command if anything in it changes
#!/bin/bash
#
# Watch current directory (recursively) for file changes, and execute
# a command when a file or directory is created, modified or deleted.
#
# Written by: Senko Rasic <senko.rasic@dobarkod.hr>
# Modified by: Grigory Stupnikov
#
# Requires Linux, bash and inotifywait (from inotify-tools package).
#
# To avoid executing the command multiple times when a sequence of
# events happen, the script waits 0.5 second after the change - if
# more changes happen, the timeout is extended by a second again.
#
# Installation:
# chmod a+rx onchange.sh
# sudo cp onchange.sh /usr/local/bin
#
# Example use - rsync local changes to the remote server:
#
# onchange.sh . echo Dir changed!
#
# Released to Public Domain. Use it as you like.
EVENTS="CREATE,CLOSE_WRITE,MOVED_FROM,MOVED_TO"
if [ -z "$1" ]; then
echo "Usage: $0 cmd ..."
exit -1;
fi
inotifywait -e "$EVENTS" -m -r --format '%:e %f' "$1" | (
WAITING="";
while true; do
LINE="";
read -t 0.5 LINE;
if test -z "$LINE"; then
if test ! -z "$WAITING"; then
echo "CHANGE";
WAITING="";
fi;
else
WAITING=1;
fi;
done) | (
while true; do
read TMP;
echo ${@:2}
${@:2}
done
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment