public
Last active

Watch current directory and execute a command if anything in it changes

  • Download Gist
onchange.sh
Shell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
#!/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>
#
# 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 one 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 rsync -avt . host:/remote/dir
#
# Released to Public Domain. Use it as you like.
#
 
EVENTS="CREATE,CLOSE_WRITE,DELETE,MODIFY,MOVED_FROM,MOVED_TO"
 
if [ -z "$1" ]; then
echo "Usage: $0 cmd ..."
exit -1;
fi
 
inotifywait -e "$EVENTS" -m -r --format '%:e %f' . | (
WAITING="";
while true; do
LINE="";
read -t 1 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 $@
$@
done
)

If you change "$@" to "eval $@" you will be able to run several commands.
Example:
onchange.sh "rsync dest orig && notify-send Sucess || notify-send Failure"

15 minutes

#!/bin/bash
if [ "$1"x = ""x ]; then
cat<<EOF
Watches for changes recursively, then goes on to execute your command
or script. It wait 2.5 minutes between executes. Good for syncing
directories or doing dynamic backups.
by Hydranix

Usage: DetectChanges "[ directory to watch ]" "[ command/script to execute ]" "[optional: time in second between executes]"
EOF
exit 0;
fi
while [ ! -f /tmp/EXITHNx ]; do
sleep 3
inotifywait -r -e create -e delete -e move "${1}" &>/dev/null
XSTA=$?
if [ "$XSTA" = "0" ]; then
eval ${2}
else
touch /tmp/EXITHNx
exit 1
fi
[[ -z ${3} ]] && sleep 150 || sleep ${3}
done
rm -f /tmp/EXITHNx

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.