bash 如何在 Linux 中创建文件侦听器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15509576/
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
How do I create a file listener in linux?
提问by Ray
I am trying to create a listener on a specific directory that kicks off a Linux command whenever a file shows up in this path. For example, whenever a file shows up in a directory like C:/home/ I would like to read a string of text from that file and then kick off another command. I was thinking of using a loop but that seems inefficient.
我正在尝试在特定目录上创建一个侦听器,每当此路径中出现文件时,该侦听器就会启动 Linux 命令。例如,每当一个文件出现在像 C:/home/ 这样的目录中时,我想从该文件中读取一串文本,然后启动另一个命令。我正在考虑使用循环,但这似乎效率低下。
回答by Jacob Parker
To get notified about events like file creation, opening, modifying etc. look into inotify. A good way to use it from bash is with the inotifywaitcommand - hereis its man page. It will block until an event you care about happens. For example:
要获得有关文件创建、打开、修改等事件的通知,请查看inotify。从 bash 使用它的一个好方法是使用inotifywait命令 -这是它的手册页。它会阻塞,直到你关心的事件发生。例如:
inotifywait -e create /path/to/watch
echo "ding!"
will ding when a file or directory gets created in that path. See the man pagefor more details.
当在该路径中创建文件或目录时,将会出现 ding。有关更多详细信息,请参阅手册页。

