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

In our Linux server, we have a background program that creates files in a specific directory. I want to receive mail when a new file is added to this directory.

I tried using Java, but it turned out to be complicated. So I'm looking for some better idea. Is there any program that can do this or a script?

+4
source share
3 answers

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

In particular, the inotifywait tool:

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

Output it via grep and send it to a Bash loop or something else. Voila!

EDIT:

Here's a quick and dirty single line:

 inotifywait -m /tmp 2>/dev/null | grep --line-buffered '/tmp/ CREATE' | while read; do echo update | mail -s "/tmp updated" john@example.com ; done 
+4
source

You want to inotify . You may also want superuser.com ;)

+2
source

In this answer, I list three Ruby libraries that allow you to browse the change directory. A script using one of these libraries and a mail library (like Pony ) will be pretty simple.

Using my library and Pony a script can 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 < noreply@mydomain.com >", to: " admin@mydomain.com ", 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 
+1
source

Source: https://habr.com/ru/post/1337987/


All Articles