bash 在脚本中使用 inotify 监控目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24567608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 10:47:17  来源:igfitidea点击:

Using inotify in a script to monitor a directory

linuxbashechomonitoringinotifywait

提问by mib1413456

I have written a bash script to monitor a particular directory "/root/secondfolder/" the script is as follows:

我写了一个bash脚本来监控一个特定的目录“/root/secondfolder/”,脚本如下:

#!/bin/sh

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

When I create a file called "fourth.txt" in "/root/secondfolder/" and write stuff to it, save and close it, it outputs the following but it does not echo "close_write":

当我在“/root/secondfolder/”中创建一个名为“fourth.txt”的文件并向其中写入内容,保存并关闭它时,它输出以下内容但不回显“close_write”:

/root/secondfolder/ CLOSE_WRITE,CLOSE fourth.txt

can someone point me in the right direction?

有人可以指出我正确的方向吗?

回答by kranteg

You are not far away from solution. If you want to use inotifywaitin your whilestatement you should not use -moption. With this option inotifywaitnever end because it's the monitoroption. So you never go into the while.

您离解决方案不远了。如果要inotifywaitwhile语句中使用,则不应使用-m选项。这个选项inotifywait永远不会结束,因为它是monitor选项。所以你永远不会进入while.

This should work :

这应该工作:

#!/bin/sh

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

回答by mib1413456

It turns out all I had to do was pipe the command into a while loop:

事实证明,我所要做的就是将命令通过管道传输到 while 循环中:

!/bin/sh

inotifywait -mqr -e close_write "/root/secondfolder/" | while read line
do
echo "close_write"
done