Ed Niell
Ed Niell

Reputation: 43

How to get know when a file is added to a directory?

In our linux server, we have a program running in the background which creates files in a certain directory. I want to get a mail when a new file is added to that dir.

I tried using Java, but that got to complex. So I'm looking for some better idea. Is there some program that can do this or a script?

Upvotes: 4

Views: 821

Answers (3)

Phrogz
Phrogz

Reputation: 303136

In this answer I list three Ruby libraries that let you watch a directory for changes. A script using one of these libraries and a mail library (like Pony) would be rather simple.

Using my library and Pony a script might be as simple as:

require 'directorywatcher'
require 'pony'

# Only watch every two minutes
my_watcher = Dir::DirectoryWatcher.new( 'uploads', 120 )
my_watcher.on_add = Proc.new do |file_name,info|
  Pony.mail(
    via:         :smtp,
    via_options: { address: 'smtp.mydomain.com', domain:'mydomain.com' },
    from:        "Upload Notifier <[email protected]>",
    to:          "[email protected]",
    subject:     "New File Uploaded!",
    body:        "A new file '#{file_name}' was just uploaded on #{info[:date]}"
  )
end
my_watcher.start_watching.join # Join the thread

Upvotes: 1

thkala
thkala

Reputation: 86333

Well, I'll go with overkill (is there such thing?) and suggest the utilities from the inotify-tools package.

More specifically the inotifywait tool:

# inotifywait -m /tmp
Setting up watches.  
Watches established.
/tmp/ OPEN,ISDIR 
/tmp/ CLOSE_NOWRITE,CLOSE,ISDIR 
.
.
.

Pipe its output through grep and send it to a Bash loop or something. Voila!

EDIT:

Here's a quick & dirty one-liner:

inotifywait -m /tmp 2>/dev/null | grep --line-buffered '/tmp/ CREATE' | while read; do echo update | mail -s "/tmp updated" [email protected]; done

Upvotes: 4

Sdaz MacSkibbons
Sdaz MacSkibbons

Reputation: 28676

You want inotify. You also might want superuser.com ;-)

Upvotes: 2

Related Questions