【发布时间】:2011-11-25 20:45:10
【问题描述】:
我是 dnotify/inotify 命令的新手。谁能帮我写一个脚本,让它持续监控一个目录并指示它有一些变化或修改。
【问题讨论】:
标签: linux linux-kernel
我是 dnotify/inotify 命令的新手。谁能帮我写一个脚本,让它持续监控一个目录并指示它有一些变化或修改。
【问题讨论】:
标签: linux linux-kernel
Inotify 本身是一个内核模块,可通过来自例如的调用访问。一个C程序。 http://www.ibm.com/developerworks/linux/library/l-ubuntu-inotify/
有一个名为 inotify-tools 的应用程序套件,其中包含:
inotifywait - 使用 inotify 等待对文件的更改
和
inotifywatch - 使用 inotify 收集文件系统访问统计信息
您可以直接从命令行使用 inotify,例如像这样持续监控主目录下的所有变化(可能会产生大量输出):
inotifywait -r -m $HOME
这是一个持续监控并对 Apache 日志活动做出反应的脚本,从 inotifywait 的 man 文件中复制:
#!/bin/sh
while inotifywait -e modify /var/log/messages; do
if tail -n1 /var/log/messages | grep httpd; then
kdialog --msgbox "Apache needs love!"
fi
done
【讨论】:
do 的内部部分时,可能会错过一些事件。
下面是我用来查看对单个文件的操作的内容。 “-m”仅在一个事件后导致监视与退出。要获取时间戳,您至少需要 3.13 版本的 inotify-tools,但如果这不重要(或在您的操作系统上不可用或难以更新),您可以跳过 timefmt 和格式选项。另一个 shell 中的“cat /etc/resolv.conf”会导致以下结果:
$ inotifywait -m --timefmt '%H:%M' --format '%T %w %e %f' /etc/resolv.conf
Setting up watches.
Watches established.
12:49 /etc/resolv.conf OPEN
12:49 /etc/resolv.conf ACCESS
12:49 /etc/resolv.conf CLOSE_NOWRITE,CLOSE
inotifywait 也有监控目录的选项,因此请查看手册页。添加 -r 用于递归监视目录的子级。
这是我在另一个窗口中键入的命令的示例,显示为“->”前缀:
$ inotifywait -mr --timefmt '%H:%M' --format '%T %w %e %f' /home/acarwile/tmpdir
Setting up watches. Beware: since -r was given, this may take a while!
Watches established.
-> cd into directory, no info
-> ls in directory
13:15 /home/acarwile/tmpdir/ OPEN,ISDIR
13:15 /home/acarwile/tmpdir/ CLOSE_NOWRITE,CLOSE,ISDIR
-> touch newfile
13:16 /home/acarwile/tmpdir/ CREATE newfile
13:16 /home/acarwile/tmpdir/ OPEN newfile
13:16 /home/acarwile/tmpdir/ ATTRIB newfile
13:16 /home/acarwile/tmpdir/ CLOSE_WRITE,CLOSE newfile
-> mv newfile renamedfile
13:16 /home/acarwile/tmpdir/ MOVED_FROM newfile
13:16 /home/acarwile/tmpdir/ MOVED_TO renamedfile
-> echo hello >renamedfile
13:16 /home/acarwile/tmpdir/ MODIFY renamedfile
13:16 /home/acarwile/tmpdir/ OPEN renamedfile
13:16 /home/acarwile/tmpdir/ MODIFY renamedfile
13:16 /home/acarwile/tmpdir/ CLOSE_WRITE,CLOSE renamedfile
-> touch renamedfile
13:17 /home/acarwile/tmpdir/ OPEN renamedfile
13:17 /home/acarwile/tmpdir/ ATTRIB renamedfile
13:17 /home/acarwile/tmpdir/ CLOSE_WRITE,CLOSE renamedfile
-> rm renamedfile
13:17 /home/acarwile/tmpdir/ DELETE renamedfile
-> cd ..; rmdir tmpdir
13:17 /home/acarwile/tmpdir/ DELETE_SELF
在完成上述操作后,我尝试重新制作 tmpdir(“mkdir tmpdir”),但没有得到任何输出。新的 tmpdir 与旧的 tmpdir 不是同一个目录。是时候 ^C 并停止它notifywait。
【讨论】:
正如我在https://superuser.com/a/747574/28782 上所说的,我制作了一个使用 inotifywait 的辅助脚本,没有直接限制: inotifyexec
使用示例(假设您已将其作为可执行文件添加到系统路径中):
inotifyexec "echo test" -r .
【讨论】: