I have a script using inotify-tool
.
This script notifies when a new file arrives in a folder. It performs some work with the file, and when done it moves the file to another folder. (it looks something along these line):
inotifywait -m -e modify "${path}" |
while read NEWFILE
work on/with NEWFILE
move NEWFILE no a new directory
done
By using inotifywait
, one can only monitor new files. A similar procedure using for OLDFILE in path
instead of inotifywait
will work for existing files:
for OLDFILE in ${path}
do
work on/with OLDFILE
move NEWFILE no a new directory
done
I tried combining the two loops. By first running the second loop. But if files arrive quickly and in large numbers there is a change that the files will arrive wile the second loop is running. These files will then not be captured by neither loop.
Given that files already exists in a folder, and that new files will arrive quickly inside the folder, how can one make sure that the script will catch all files?
Once
inotifywait
is up and waiting, it will print the messageWatches established.
to standard error. So you need to go through existing files after that point.So, one approach is to write something that will process standard error, and when it sees that message, lists all the existing files. You can wrap that functionality in a function for convenience:
and then write:
Notes:
>(...)
notation that I used, it's called "process substitution"; see https://www.gnu.org/software/bash/manual/bash.html#Process-Substitution for details.inotifywait
starts up, thenlist-existing-and-follow-modify
may list it twice. But you can easily handle that inside yourwhile
-loop by usingif [[ -e "$file" ]]
to make sure the file still exists before you operate on it.inotifywait
options are really quite what you want;modify
, in particular, seems like the wrong event. But I'm sure you can adjust them as needed. The only change I've made above, other than switching to long options for clarity/explicitly and adding--
for robustness, is to add--format %f
so that you get the filenames without extraneous details.inotifywait
to use a separator other than newlines, so, I just rolled with that. Make sure to avoid filenames that include newlines.