inotify 是 Linux 内核提供的一种文件系统事件监控机制,它可以用来监控文件或目录的变化,如创建、删除、修改等。在 Debian 系统中,你可以使用 inotify-tools 这个软件包来方便地使用 inotify。
以下是在 Debian 系统中使用 inotify 的步骤:
sudo apt update
inotify-tools:sudo apt install inotify-tools
inotifywait 是 inotify-tools 中的一个命令行工具,用于等待并报告文件系统事件。
inotifywait [选项] 目录
例如,监控当前目录下的所有文件变化:
inotifywait -m .
-m:监控模式,持续监控目录。-r:递归监控子目录。-e:指定要监控的事件,如 create, delete, modify 等。-q:安静模式,不输出冗余信息。--format:自定义输出格式。例如,监控当前目录及其子目录下的所有文件创建事件,并输出详细信息:
inotifywait -m -r -e create --format '%w%f %e' .
inotifywatch 是另一个 inotify-tools 中的工具,用于统计文件系统事件的发生次数。
inotifywatch [选项] 目录 [时间间隔]
例如,监控当前目录下的所有文件变化,并每 5 秒输出一次统计信息:
inotifywatch -m -r -e create,delete,modify --timefmt '%Y-%m-%d %H:%M:%S' --format '%w%f %e %T' 5 .
假设你想监控 /home/user/documents 目录下的所有文件创建事件,并在事件发生时执行一个脚本 handle_new_file.sh,你可以这样做:
创建脚本 handle_new_file.sh:
#!/bin/bash
echo "New file created: $1"
# 在这里添加你想要执行的操作
赋予脚本执行权限:
chmod +x handle_new_file.sh
使用 inotifywait 监控目录并执行脚本:
inotifywait -m -r -e create --format '%w%f' /home/user/documents | while read FILE
do
./handle_new_file.sh "$FILE"
done
通过这些步骤,你可以在 Debian 系统中方便地使用 inotify 来监控文件系统的变化。