Search code examples
bashshellcygwinsh

I need a script to repeatedly poll through a directory tree, find all newly modified files, and execute a command on each such file


I need to write a script to repeatedly poll through a directory tree, find all newly modified files, and execute a command on each such file (say, encryption, archiving, etc.)

By "newly modified files" I mean files that were modified since last polled.

I specified "bash" tag, but it can be any shell (that runs under Cygwin).

I suppose I could rename files that have already been processed; but I wonder if there can be a cleaner solution.


Solution

  • dirname="/home/me/xxx"
    lockfile="/tmp/me.lockfile.$$"
    
    find $dirname -type f | xargs command
    touch $lockfile
    
    while true
    do
        find $dirname -type f -newer $lockfile | xargs command
        touch $lockfile
        sleep 1
    done
    

    Note that there is a problem with this solution - there is a race condition between the call to find and the touch of the lockfile but this is probably good enough for most practical purposes.

    If money or lives are at stake you'll need to come up with something more robust