在CentOS系统中,inotify
是一个用于监控文件系统事件的Linux内核子系统。你可以使用inotify-tools
这个软件包来方便地监控文件变化。以下是如何在CentOS上安装和使用inotify-tools
的步骤:
更新系统包列表:
sudo yum update -y
安装inotify-tools:
sudo yum install inotify-tools -y
inotifywait
是inotify-tools
中的一个命令行工具,可以用来等待并报告文件系统事件。以下是一些常用的命令示例:
inotifywait -m /path/to/file -e modify,attrib,close_write,move,create,delete
-m
:持续监控。/path/to/file
:要监控的文件路径。-e
:指定要监控的事件类型,例如modify
(修改)、attrib
(属性变化)、close_write
(关闭写入)、move
(移动)、create
(创建)、delete
(删除)。inotifywait -m /path/to/directory -e create,delete,modify,move
/path/to/directory
:要监控的目录路径。你可以使用多个inotifywait
命令并行运行来监控多个文件或目录:
inotifywait -m /path/to/file1 -e modify &
inotifywait -m /path/to/file2 -e modify &
inotifywait -m /path/to/directory -e create,delete,modify,move &
你可以将inotifywait
的输出重定向到一个日志文件中:
inotifywait -m /path/to/file -e modify,attrib,close_write,move,create,delete >> /var/log/inotify.log 2>&1 &
以下是一个简单的示例脚本,用于监控指定目录下的所有文件变化,并将输出记录到日志文件中:
#!/bin/bash
LOGFILE="/var/log/inotify.log"
DIRECTORY="/path/to/directory"
# 清空日志文件
> $LOGFILE
# 监控目录变化
inotifywait -m -r -e create,delete,modify,move --format '%w%f %e' "$DIRECTORY" >> $LOGFILE 2>&1 &
PID=$!
# 等待脚本终止
wait $PID
将上述脚本保存为monitor.sh
,然后运行:
chmod +x monitor.sh
./monitor.sh
这样,你就可以持续监控指定目录下的文件变化,并将输出记录到/var/log/inotify.log
文件中。
通过这些步骤,你可以在CentOS系统上使用inotify
来监控文件变化。