mojojojo
mojojojo

Reputation: 57

OS X script to send email when new file is created

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?

Upvotes: 0

Views: 730

Answers (3)

Gordon Davisson
Gordon Davisson

Reputation: 125708

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"

Upvotes: 1

Jon Snyder
Jon Snyder

Reputation: 2009

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

Upvotes: 0

Marcelo Cantos
Marcelo Cantos

Reputation: 185852

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

Upvotes: 1

Related Questions