使用 inotify-tools 在多个目录中递归地连续检测新文件

Dav*_*ter 21 linux email ubuntu inotify

我刚刚安装了inotify-tools。我想在多个目录中递归地使用通知工具不断检测新文件,并使用后缀发送电子邮件。我可能可以使用 postfix 部分处理发送电子邮件。在尝试检测新文件时,我只是想找出解决此问题的最佳方法。因为有时一次添加多个文件。

小智 46

inotifywaitinotify-tools 的一部分)是实现您目标的正确工具,无论同时创建多个文件,它都会检测到它们。

这是一个示例脚本:

#!/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
Run Code Online (Sandbox Code Playgroud)

inotifywait将使用这些选项。

-m无限期地监视目录,如果您不使用此选项,一旦检测到新文件,脚本将结束。

-r将递归监视文件(如果有很多目录/文件,可能需要一段时间才能检测到新创建的文件)

-e create是指定要监视的事件的选项,在您的情况下,应该创建它以处理新文件

--format '%w%f'将以 /complete/path/file.name 格式打印出文件

“${MONITORDIR}”是包含我们之前定义的监控路径的变量。

因此,如果创建了新文件,inotifywait 将检测到它并将输出(/complete/path/file.name)打印到管道,同时将该输出分配给变量 NEWFILE

在 while 循环中,您将看到一种使用mailx 实用程序将邮件发送到您的地址的方法,该实用程序应该可以与您的本地 MTA(在您的情况下,Postfix)一起正常工作。

如果你想监视多个目录,inotifywait 不允许它,但你有两个选择,为每个目录创建一个脚本来监视或在脚本中创建一个函数,如下所示:

#!/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" &
Run Code Online (Sandbox Code Playgroud)

  • @sahsanu 我不同意整个“网络礼节”的事情。每个人都从自己的角度回答问题。答案之间没有重叠,也没有重写的答案。当问题如此具体时,答案不可能以这种方式不同。非常感谢您抽出宝贵时间详细回答问题。对于像我这样刚刚了解这一切的人来说,这所提供的帮助超出了您的了解。你为我节省了无数个小时。 (4认同)

har*_*ymc 8

使用inotifywait,例如:

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
Run Code Online (Sandbox Code Playgroud)

有关更多信息和示例,请参阅文章
How to use inotify-tools to trigger scripts on filesystem events

  • @Savageman 正是出于这个原因,**强烈** 不鼓励使用大写变量名作为您自己的变量。大写变量名保留供系统使用;您自己的变量应使用小写。 (2认同)