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?
Asked
Active
Viewed 4.5k times
4 Answers
24
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.

Evi1M4chine
- 6,992
- 1
- 24
- 18
-
1Thanks, best answer so far. I was sure there was something nifty with inotify and this is exactly it.Works like a charm. – akostadinov Jan 31 '13 at 20:09
-
ADDENDUM: If you want to avoid thrashing your SSD, put the file in a `tmpfs` mount. My entire `/tmp` is a `tmpfs` for that very reason. Also helps with the clean up, because a reboot suffices to empty it. – Evi1M4chine Mar 03 '23 at 16:17
24
Look at inotify.
With inotify you can watch a directory for file creation.

Douglas Leeder
- 52,368
- 9
- 94
- 137
-
3Inotify does not support recursively watching directories, meaning that a separate inotify watch must be created for every subdirectory. Keep this in mind. – Jason Dec 10 '13 at 17:07
-
Also see package called [incron](http://inotify.aiken.cz/?section=incron&page=why) and its [man page](http://linux.die.net/man/5/incrontab). I'm not sure how it handles sub-folders. – BeowulfNode42 Apr 14 '14 at 05:46
-
1No, incron does not handle sub-folders, it totally failed on an appropriate "indiegogo" campaign, and incron dozed off in 2012. Sad, but it reached a blind-alley. I really hope, inotify will stay ;-) – Frunsi Oct 26 '14 at 00:53
0
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.

Nate
- 18,892
- 27
- 70
- 93
-
If you want to process them ASAP, there is no way around inotify. – Aaron Digulla Feb 04 '09 at 14:20
0
fschange (Linux File System Change Notification) is a perfect solution, but it needs to patch your kernel

Matt Wilko
- 26,994
- 10
- 93
- 143

felix021
- 1,936
- 3
- 16
- 20
-
5Note the warning at the top of the article, ```fschange is an alternative to inotify that [was] implemented before inotify became part of the mainline Linux kernel. ``` – TechplexEngineer Jan 09 '13 at 17:45