使用inotify监视目录但无法正常工作100%


10

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

#!/bin/sh

while inotifywait -mr -e close_write "/root/secondfolder/"
do
    echo "close_write"
done

当我创建一个名为fourth.txtin 的文件/root/secondfolder/并将其写入内容,保存并关闭时,它输出以下内容:

/root/secondfolder/ CLOSE_WRITE,CLOSE fourth.txt

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

Answers:


16

inotifywait -m 是“监视器”模式:它永远不会退出。外壳程序将运行它,并等待退出代码知道是否运行循环的主体,但这永远不会发生。

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

while inotifywait -r -e close_write "/root/secondfolder/"
do
    echo "close_write"
done

产生

Setting up watches.  Beware: since -r was given, this may take a while!
Watches established.
/root/secondfolder/ CLOSE_WRITE,CLOSE bar
close_write
Setting up watches.  Beware: since -r was given, this may take a while!
Watches established.
...

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


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

#!/bin/bash

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

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


2
将命令插入循环工作,谢谢!
mib1413456 2014年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.