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

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


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 /tmpSetting 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" john@example.com; done


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 minutesmy_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 <noreply@mydomain.com>",    to:          "admin@mydomain.com",    subject:     "New File Uploaded!",    body:        "A new file '#{file_name}' was just uploaded on #{info[:date]}"  )endmy_watcher.start_watching.join # Join the thread