poll directory for changes in bash

Here is some quick bash to watch all the files under a directory and do something when one of them changes:

% directory_sum() { stat $( find ${*} -type f | grep -vw .swp ) | sha1sum  | awk '{print $1}' ; };
% directory_watcher() { local dir=${1} ; shift ; local delay=${1} ; shift ; local action=${*} ; local current="" ; while true ; do next=$( directory_sum ${dir} ) ; if [ "${current}" != "${next}" ] ; then echo modification: ${action} ; current=${next} ; fi ; % echo -n . ; sleep ${delay} ; done; };
% reset ; directory_watcher us 5 haxe compile.hxml

So… this has some trickz:

  • define functions in the shell which can then used like any other command
  • the syntax for jamming all that on one line is nutty!
  • using find with stat and sha1sum is a cheap (to write, not necessarily to run!) way to check the tree for mods
  • the shift command is a nice way to deal with arguments to functions

In the interests of sanity, I will bust that out somewhat for legibility:

directory_sum() { 
    stat $( find ${*} -type f | grep -vw .swp ) | sha1sum  | awk '{print $1}' 
}
directory_watcher() { 
    local dir=${1}
    shift
    local delay=${1}
    shift 
    local action=${*} 
    local current="" 
    while true ; do 
        next=$( directory_sum ${dir} ) 
        if [ "${current}" != "${next}" ] ; then 
                echo modification: ${action}
                ${action}
                 current=${next} 
        fi
        echo -n .
        sleep ${delay}
    done
}

If you want to use it as stands:

% wget http://brianin3d.googlepages.com/directory_watcher.sh
% source directory_watcher.sh
% directory_watcher 5 haxe compile.hxml

Once the file is source suddenly I can use these functions in other scripts, on the cli or whatever just like any other command. They are a nice middle-ground between copy-pasta and creating a different script for each discrete piece of functionality (that’s my definition of a function in case you are wondering).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: