Inotifywait – Watch Directory for Specific File Extensions

filesystemsinotifymonitoringshellshell-script

I have seen this answer.

You should consider using inotifywait, as an example:

inotifywait -m /path -e create -e moved_to |
    while read path action file; do
        echo "The file '$file' appeared in directory '$path' via '$action'"
        # do something with the file
    done

My question is that, the above script watches a directory for creation of files of any type, but how do I modify the inotifywait command to report only when a file of certain type/extension is created (or moved into the directory) – e.g. it should report when any .xml file is created.

WHAT I TRIED:

I have run the inotifywait --help command, and have read the command line options. It has --exclude <pattern> and --excludei <pattern> commands to EXCLUDE files of certain types (by using regEx), but I need a way to INCLUDE just the files of a certain type/extension.

Best Answer

how do I modify the inotifywait command to report only when a file of certain type/extension is created

Please note that this is untested code since I don't have access to inotify right now. But something akin to this ought to work:

inotifywait -m /path -e create -e moved_to |
    while read path action file; do
        if [[ "$file" =~ .*xml$ ]]; then # Does the file end with .xml?
            echo "xml file" # If so, do your thing here!
        fi
    done
Related Question