Linux – Continuously detect new file(s) with inotify-tools within multiple directories recursively

emailinotifylinuxUbuntu

I just installed inotify-tools. I would like to continuously detect new file(s) with notify-tools within multiple directories recursively, and send an email using postfix. I can probably handle the send an email using postfix part. I'm just trying to figure out the best way to go about this when trying to detecting new file(s). Because sometimes multiple files are added at once.

Best Answer

inotifywait (part of inotify-tools) is the right tool to accomplish your objective, doesn't matter that several files are being created at the same time, it will detect them.

Here a sample script:

#!/bin/sh
MONITORDIR="/path/to/the/dir/to/monitor/"
inotifywait -m -r -e create --format '%w%f' "${MONITORDIR}" | while read NEWFILE
do
        echo "This is the body of your mail" | mailx -s "File ${NEWFILE} has been created" "yourmail@addresshere.tld"
done

inotifywait will use these options.

-m to monitor the dir indefinitely, if you don't use this option, once it has detected a new file the script will end.

-r will monitor files recursively (if there are a lot of dirs/files it could take a while to detect the new created files)

-e create is the option to specify the event to monitor and in your case it should be create to take care about new files

--format '%w%f' will print out the file in the format /complete/path/file.name

"${MONITORDIR}" is the variable containing the path to monitor that we have defined before.

So in the event that a new file is created, inotifywait will detect it and will print the output (/complete/path/file.name) to the pipe and while will assign that output to variable NEWFILE.

Inside the while loop you will see a way to send a mail to your address using the mailx utility that should work fine with your local MTA (in your case, Postfix).

If you want to monitor several directories, inotifywait doesn't allow it but you have two options, create a script for every dir to monitor or create a function inside the script, something like this:

#!/bin/sh
MONITORDIR1="/path/to/the/dir/to/monitor1/"
MONITORDIR2="/path/to/the/dir/to/monitor2/"
MONITORDIRX="/path/to/the/dir/to/monitorx/"    

monitor() {
inotifywait -m -r -e create --format "%f" "$1" | while read NEWFILE
do
        echo "This is the body of your mail" | mailx -s "File ${NEWFILE} has been created" "yourmail@addresshere.tld"
done
}
monitor "$MONITORDIR1" &
monitor "$MONITORDIR2" &
monitor "$MONITORDIRX" &
Related Question