使用 inotify 监控目录但不能 100% 工作

mib*_*456 12 shell shell-script inotify

我编写了一个 bash 脚本来监视特定目录/root/secondfolder/

#!/bin/sh

while inotifywait -mr -e close_write "/root/secondfolder/"
do
    echo "close_write"
done
Run Code Online (Sandbox Code Playgroud)

当我创建一个名为fourth.txt/root/secondfolder/和写的东西给它,保存并关闭它,它输出以下内容:

/root/secondfolder/ CLOSE_WRITE,CLOSE fourth.txt
Run Code Online (Sandbox Code Playgroud)

但是,它不会回显“close_write”。这是为什么?

Mic*_*mer 19

inotifywait -m 是“监控”模式:它永远不会退出。shell 运行它并等待退出代码以知道是否运行循环体,但这永远不会发生。

如果您删除-m,它将起作用:

while inotifywait -r -e close_write "/root/secondfolder/"
do
    echo "close_write"
done
Run Code Online (Sandbox Code Playgroud)

产生

while inotifywait -r -e close_write "/root/secondfolder/"
do
    echo "close_write"
done
Run Code Online (Sandbox Code Playgroud)

默认情况下, inotifywait 将“在第一个事件发生后退出”,这是您在循环条件中想要的。


相反,您可能更喜欢阅读以下标准输出inotifywait

#!/bin/bash

while read line
do
    echo "close_write: $line"
done < <(inotifywait -mr -e close_write "/tmp/test/")
Run Code Online (Sandbox Code Playgroud)

这个(bash)脚本将使用进程替换inotifywait命令的每个输出行读入$line循环内的变量。它避免了每次在循环中设置递归监视,这可能很昂贵。如果你不能使用bash,可以通过管道命令进入死循环,而不是:inotifywait ... | while read line ...inotifywait在此模式下为每个事件生成一行输出,因此循环为每个事件运行一次。

  • 将命令放入循环中有效,谢谢! (2认同)