小智 46
inotifywait(inotify-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)
使用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。
| 归档时间: |
|
| 查看次数: |
58906 次 |
| 最近记录: |