Inotifywait for large directories

2020-08-02 03:18发布

In the inotifywait man changes the following is stated

-r, --recursive Watch all subdirectories of any directories passed as arguments. Watches will be set up recursively to an unlimited depth. Symbolic links are not tra‐versed. Newly created subdirectories will also be watched.

Warning: If you use this option while watching the root directory of a large tree, it may take quite a while until all inotify watches are established, and events will not be received in this time. Also, since one inotify watch will be established per subdirectory, it is possible that the maximum amount of inotify watches per user will be reached. The default maximum is 8192; it can be increased by writing to /proc/sys/fs/inotify/max_user_watches.

I take this to mean that every time inotifywait is called, there is a delay for large directories. Therefore, constantly monitoring a large directory with monitor function like so

inotifywait -m /home/user/Documents

is more efficient than manually looping through the directory like so (from an example in the man pages)

while inotifywait /home/user/Documents; do
 #Do Something for each file change
done

as every iteration of the while loop you have to set up inotifywait again. But with the first option, I can't execute based on the return. Ideally what I want is a callback function like so

inotifywait -m --callback ./callback.sh /home/user/Documents

so callback.sh gets called each time with the return value of inotifywait. How would I implement this?

1条回答
Emotional °昔
2楼-- · 2020-08-02 03:33

You can pipe it like:

inotifywait -m /my/directory | while read LINE; do ./do_something.sh $LINE; done

Keep in mind that you get many events for certain operations, each of which will trigger the launch of your script.

You can also use perl or some other language to use the API directly, which gives you tons of flexibility.

查看更多
登录 后发表回答