views:

40

answers:

3

How can I monitor a directory, and send an email whenever a new file is created?

I currently have a script running daily which uses find to search for all files in a directory with a last modified date newer than an empty timestamp file:

#!/bin/bash
folderToWatch="/Path/to/files"
files=files.$$
find $folderToWatch/* -newer timestamp -print > $files
if [ -s "$files" ]
then
# SEND THE EMAIL
touch timestamp

Unfortunately, this also sends emails when files are modified. I know creation date is not stored in Unix, but this information is available in Finder, so can I somehow modify my script to use that information date rather than last modified?

+1  A: 

You could maintain a manifest:

new_manifest=/tmp/new_manifest.$$
(cd $folderToWatch; find .) > $new_manifest
diff manifest $new_manifest | perl -ne 'print "$1\n" if m{^> \./(.*)}' > $files
mv -f $new_manifest manifest
Marcelo Cantos
Ah, very true! I will go this route if the "created date" attribute is not accessible.
mojojojo
FYI, this approach is more reliable that "created date" since files can sometimes be created with older timestamps.
Marcelo Cantos
The only files I really care about are ones uploaded via FTP, which, in my testing, all have creation dates of the time of upload. But that is a good point; any files transferred via Finder don't get new creation dates.
mojojojo
A: 

You may be interested in looking at the change time.

if test `find "text.txt" -cmin +120`
then
    echo old enough
fi

See: How do i check in bash whether a file was created more than x time ago

Jon Snyder
This should present the same issue. Files created, say, two weeks ago but updated today would still show up.
mojojojo
+1  A: 

Snow Leopard's find command has a -Bnewer primary that compares the file's "birth time" (aka inode creation time) to the timestamp file's modify time, so it should do pretty much what you want. I'm not sure exactly when this feature was added; it's there in 10.6.4, not there in 10.4.11, and I don't have a 10.5 machine handy to look at. If you need this to work on an earlier version, you can use stat to fake it, something like this:

find "$folderToWatch"/* -newer timestamp -print | \
    while IFS="" read file; do
        if [[ $(stat -f %B "$file") > $(stat -f %m timestamp) ]]; then
            printf "%s\n" "$file"
        fi
    done >"$files"
Gordon Davisson
Awesome! Thank you. *facepalm* I should have gone to the manual.
mojojojo