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
Using inotify in a script to monitor a directory
提问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 inotifywait
in your while
statement you should not use -m
option. With this option inotifywait
never end because it's the monitor
option. So you never go into the while
.
您离解决方案不远了。如果要inotifywait
在while
语句中使用,则不应使用-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