Nate
Nate

Reputation: 19442

Monitor Directory for Changes

Much like a similar SO question, I am trying to monitor a directory on a Linux box for the addition of new files and would like to immediately process these new files when they arrive. Any ideas on the best way to implement this?

Upvotes: 22

Views: 45818

Answers (5)

developer.g
developer.g

Reputation: 3144

Look at entr or man entr.

With entr, you can watch a directory for file creation or modification easier than inotify.

Upvotes: 0

anon
anon

Reputation:

First make sure inotify-tools in installed.

Then use them like this:

logOfChanges="/tmp/changes.log.csv" # Set your file name here.

# Lock and load
inotifywait -mrcq $DIR > "$logOfChanges" &
IN_PID=$$

# Do your stuff here
...

# Kill and analyze
kill $IN_PID
while read entry; do
   # Split your CSV, but beware that file names may contain spaces too.
   # Just look up how to parse CSV with bash. :)
   path=... 
   event=...
   ...  # Other stuff like time stamps?
   # Depending on the event…
   case "$event" in
     SOME_EVENT) myHandlingCode path ;;
     ...
     *) myDefaultHandlingCode path ;;
done < "$logOfChanges"

Alternatively, using --format instead of -c on inotifywait would be an idea.

Just man inotifywait and man inotifywatch for more infos.

You can also use incron and use it to call a handling script.

Upvotes: 25

felix021
felix021

Reputation: 2018

fschange (Linux File System Change Notification) is a perfect solution, but it needs to patch your kernel

Upvotes: 0

Douglas Leeder
Douglas Leeder

Reputation: 53310

Look at inotify.

With inotify you can watch a directory for file creation.

Upvotes: 24

Nate
Nate

Reputation: 19442

One solution I thought of is to create a "file listener" coupled with a cron job. I'm not crazy about this but I think it could work.

Upvotes: 0

Related Questions