0

I want to use inotifywait to run code upon the creation of a file with a known fixed filename. This answer correctly explains that I cannot run inotifywait directly against a file that does not yet exist and that instead, I should run inotifywait against the parent directory, with an include argument that contains a suitable regex to match the specified filename. If I use the regular expression that that answer suggests, however, I find that other filenames match:

inotifywait -m -e close_write --format %f --include 'hello\.txt' .

# (Then, in another terminal...)
touch hello.txt   # Prints hello.txt - this is good.
touch ahello.txt  # Prints ahello.txt - this is bad.
touch hello.txta  # Prints hello.txta - this is bad.
touch ahello.txta # Prints ahello.txta - this is bad.

"That's easy to fix", I say to myself. "I'll just add in the usual metacharacters to mark the start and end of the string."

inotifywait -m -e close_write --format %f --include '^hello\.txt$' .

# (Then, in another terminal...)
touch ahello.txta  # Prints nothing - this is good.
touch ahello.txt   # Prints nothing - this is good.
touch hello.txta   # Prints nothing - this is good.
touch hello.txt    # Prints nothing - this is bad.

man inotifywait clearly states --include <pattern> will "process events only for the subset of files whose filenames match the specified POSIX regular expression, case sensitive." and I can see the filenames (as inotifywait sees them) printed in the first block of code above: when I typed in touch hello.txt, inotifywait printed hello.txt so I know that inotifywait thinks that the filename is hello.txt.

Why is my regular expression ^hello\.txt$ not matching the filename hello.txt? What should I be using instead?

1 Answer 1

2

Despite inotifywait --format %f printing hello.txt, that it NOT what it thinks is the filename. What it thinks is the filename is ./hello.txt. Hence the correct regex is ^\./hello\.txt$:

inotifywait -m -e close_write --format %f --include '^\./hello\.txt$' .

# (Then, in another terminal...)
touch hello.txt   # Prints hello.txt - this is good.
touch ahello.txt  # Prints nothing - this is good.
touch hello.txta  # Prints nothing - this is good.  
touch ahello.txta # Prints nothing - this is good.   

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.