inotify
是 Linux 系统中一个用于监控文件系统事件的工具
-
首先,确保您的系统已安装了
inotify-tools
。如果尚未安装,请使用以下命令之一进行安装:对于基于 Debian 的系统(如 Ubuntu):
sudo apt-get update sudo apt-get install inotify-tools
对于基于 RHEL 的系统(如 CentOS):
sudo yum install inotify-tools
-
创建一个名为
monitor.sh
的脚本文件:touch monitor.sh chmod +x monitor.sh
-
使用文本编辑器打开
monitor.sh
,然后将以下内容粘贴到文件中:#!/bin/bash # 检查参数数量 if [ "$#" -ne 1 ]; then echo "Usage: $0
" exit 1 fi directory=$1 # 检查给定的目录是否存在 if [ ! -d "$directory" ]; then echo "Error: Directory $directory does not exist." exit 1 fi # 使用 inotifywait 监控目录中的更改 inotifywait -m -r -e create -e modify -e moved_to "$directory" | while read event file; do echo "Event: $event, File: $file" done 这个脚本将监控给定目录中的创建、修改和移动事件。
-
保存并关闭文件。现在,您可以通过运行以下命令来启动脚本:
./monitor.sh /path/to/directory
将
/path/to/directory
替换为您要监控的目录路径。
现在,monitor.sh
脚本将使用 inotify
监控您指定的目录,并在发生文件系统事件时输出相应信息。要停止脚本,请在运行脚本的终端中按 Ctrl + C
。