inotify

How to use inotifywait to wait till a file is created and is written content with timeout


I'm using shell command in redhat ubi-minimal. I want to monitor a file "./hello.txt", which does not exist yet. I want to use inotifywait to monitor this file, and wait until either ./hello.txt is created and being written some non-empty content in it, or a fixed timeout.

Following inotifywait's man page, I tried:

inotifywait -m -e create -r --fromfile ./hello.txt -t 30

with -m -e create specifying that this command executes indefinitely until create occur.

But it only gives:

Couldn't open ./hello.txt: No such file or directory
No files specified to watch!

I wonder how to specify the flags of inotifywait to achieve what I'm expecting.


Solution

  • You cannot wait for ./hello.txt because it doesn't exist yet, so the kernel has no node to attach the inotify object to.

    You need to wait on the parent directory (.). The problem is that you have to find a way to filter out only the specific file. If you have at least version 3.20.1 of inotifywait, you can just use the option --include to pass a regex with the name of your file. If you don't, ...well, you can try to use the option --exclude and write a reversed regex or you can write a script to filter the result externally. Both of these options are rather inconvenient. Answers to this question describe various ways of making the filter: https://unix.stackexchange.com/q/323901/133542.

    If you have the new version, the command will look like this:

    inotifywait -e close_write -t 30 --include 'hello\.txt' .
    

    A few remarks: