0

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.

Irina Rapoport
  • 1,404
  • 1
  • 20
  • 37
  • possible duplicate of [Bash script, watch folder, execute command](http://stackoverflow.com/questions/6475252/bash-script-watch-folder-execute-command) – tripleee Feb 07 '14 at 20:26

1 Answers1

2
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

Nick
  • 2,012
  • 1
  • 13
  • 10
  • Thank you! I like that! I don't think multithreading is an issue here, since I can run only one instance of this process. The first "touch $lockfile" is a problem though, because I want to continue where I left every time the script restarts. – Irina Rapoport Feb 07 '14 at 23:01