Linux - 借助 inotifywait,轻松实现 Linux 文件/目录事件监听-LMLPHP

inotify-tools 依赖包


[root@VM-24-3-centos ~]# yum install inotify-tools
Loaded plugins: fastestmirror, langpacks
Repository epel is listed more than once in the configuration
Determining fastest mirrors
......
......
......
Resolving Dependencies
--> Running transaction check
---> Package inotify-tools.x86_64 0:3.14-9.el7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

=======================================================================================================================================
 Package                             Arch                         Version                             Repository                  Size
=======================================================================================================================================
Installing:
 inotify-tools                       x86_64                       3.14-9.el7                          epel                        51 k

Transaction Summary
=======================================================================================================================================
Install  1 Package

Total download size: 51 k
Installed size: 111 k
Is this ok [y/d/N]: y
Downloading packages:
inotify-tools-3.14-9.el7.x86_64.rpm                                                                             |  51 kB  00:00:00
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : inotify-tools-3.14-9.el7.x86_64                                                                                     1/1
  Verifying  : inotify-tools-3.14-9.el7.x86_64                                                                                     1/1

Installed:
  inotify-tools.x86_64 0:3.14-9.el7

Complete!
[root@VM-24-3-centos ~]#


使用


[root@VM-24-3-centos ~]# inotifywait  --help
inotifywait 3.14
Wait for a particular event on a file or set of files.
Usage: inotifywait [ options ] file1 [ file2 ] [ file3 ] [ ... ]
Options:
        -h|--help       Show this help text.
        @<file>         Exclude the specified file from being watched.
        --exclude <pattern>
                        Exclude all events on files matching the
                        extended regular expression <pattern>.
        --excludei <pattern>
                        Like --exclude but case insensitive.
        -m|--monitor    Keep listening for events forever.  Without
                        this option, inotifywait will exit after one
                        event is received.
        -d|--daemon     Same as --monitor, except run in the background
                        logging events to a file specified by --outfile.
                        Implies --syslog.
        -r|--recursive  Watch directories recursively.
        --fromfile <file>
                        Read files to watch from <file> or `-' for stdin.
        -o|--outfile <file>
                        Print events to <file> rather than stdout.
        -s|--syslog     Send errors to syslog rather than stderr.
        -q|--quiet      Print less (only print events).
        -qq             Print nothing (not even events).
        --format <fmt>  Print using a specified printf-like format
                        string; read the man page for more details.
        --timefmt <fmt> strftime-compatible format string for use with
                        %T in --format string.
        -c|--csv        Print events in CSV format.
        -t|--timeout <seconds>
                        When listening for a single event, time out after
                        waiting for an event for <seconds> seconds.
                        If <seconds> is 0, inotifywait will never time out.
        -e|--event <event1> [ -e|--event <event2> ... ]
                Listen for specific event(s).  If omitted, all events are
                listened for.

Exit status:
        0  -  An event you asked to watch for was received.
        1  -  An event you did not ask to watch for was received
              (usually delete_self or unmount), or some error occurred.
        2  -  The --timeout option was given and no events occurred
              in the specified interval of time.

Events:
        access          file or directory contents were read
        modify          file or directory contents were written
        attrib          file or directory attributes changed
        close_write     file or directory closed, after being opened in
                        writeable mode
        close_nowrite   file or directory closed, after being opened in
                        read-only mode
        close           file or directory closed, regardless of read/write mode
        open            file or directory opened
        moved_to        file or directory moved to watched directory
        moved_from      file or directory moved from watched directory
        move            file or directory moved to or from watched directory
        create          file or directory created within watched directory
        delete          file or directory deleted within watched directory
        delete_self     file or directory was deleted
        unmount         file system containing file or directory unmounted
[root@VM-24-3-centos ~]#

常用选项包括:

  • -m​:以持续监视模式运行,即持续监视文件并输出事件。
  • ​-r​:递归监视指定目录及其子目录中的文件。
  • ​-e <event>​:指定要监视的特定事件类型。可以使用多个 -e​ 选项来指定多个事件类型。
  • ​-q​:静默模式,只输出事件信息。
  • ​-s <seconds>​:设置事件之间的最小时间间隔。

使用 inotifywait 命令时,它会持续监视指定的文件或目录,并在事件发生时输出相关信息。可以根据需要处理输出,例如执行其他命令或触发脚本。


示例

监视单个文件的事件:


[root@VM-24-3-centos ~]# inotifywait -e modify -e create a1.txt
Setting up watches.
Watches established.




以上命令将监视 myfile.txt​ 文件的修改和创建事件。

监视单个目录的事件:


[root@VM-24-3-centos ~]# inotifywait -e modify -e create /root
Setting up watches.
Watches established.






以上命令将监视 mydir/​ 目录中文件的修改和创建事件。

监视多个文件或目录的事件:


[root@VM-24-3-centos ~]# touch a1.txt
[root@VM-24-3-centos ~]# touch a2.txt
[root@VM-24-3-centos ~]# inotifywait -e modify -e create a1.txt a2.txt /root
Setting up watches.
Watches established.
^C

以上命令将同时监视 a1.txt​、a2.txt​ 和 mydir/​ 中的文件的修改和创建事件。

如果监视的是目录,则 inotifywait 命令也会观察该目录中的子目录。可以使用 -r​ 选项来递归地监视目录及其子目录中的文件。


#!/bin/bash
# 指定监控目录
directory="/root"
# 监控目录下的文件变更
while inotifywait -r -m  -e create,modify  $directory; do
 # 处理文件变更事件
 echo "File event: $?"
 inotifywait -r  -e create,modify  $directory | while read line; do
   # 输出事件详细信息
   echo "$line"
 done
done

Linux - 借助 inotifywait,轻松实现 Linux 文件/目录事件监听-LMLPHP

08-18 09:05