]> git.friedersdorff.com Git - max/saltfiles.git/blob - states/utils/files/onchanges.bash
Configure some moar
[max/saltfiles.git] / states / utils / files / onchanges.bash
1 #!/bin/bash
2 #
3 # Watch current directory (recursively) for file changes, and execute
4 # a command when a file or directory is created, modified or deleted.
5 #
6 # Written by: Senko Rasic <senko.rasic@dobarkod.hr>
7 #
8 # Requires Linux, bash and inotifywait (from inotify-tools package).
9 #
10 # To avoid executing the command multiple times when a sequence of
11 # events happen, the script waits one second after the change - if
12 # more changes happen, the timeout is extended by a second again.
13 #
14 # Installation:
15 #     chmod a+rx onchange.sh
16 #     sudo cp onchange.sh /usr/local/bin
17 #
18 # Example use - rsync local changes to the remote server:
19 #    
20 #    onchange.sh rsync -avt . host:/remote/dir
21 #
22 # Released to Public Domain. Use it as you like.
23 #
24
25 EVENTS="CREATE,CLOSE_WRITE,DELETE,MODIFY,MOVED_FROM,MOVED_TO"
26
27 if [ -z "$1" ]; then
28     echo "Usage: $0 cmd ..."
29     exit -1;
30 fi
31
32 inotifywait -e "$EVENTS" -m -r --format '%:e %f' . | (
33     WAITING="";
34     while true; do
35         LINE="";
36         read -t 1 LINE;
37         if test -z "$LINE"; then
38             if test ! -z "$WAITING"; then
39                     echo "CHANGE";
40                     WAITING="";
41             fi;
42         else
43             WAITING=1;
44         fi;
45     done) | (
46     while true; do
47         read TMP;
48         echo $@
49         eval $@
50     done
51 )