inotify 是 Linux 系統中一個用于監控文件系統事件的工具
要在 Linux 中使用 inotify 監控文件系統事件,請按照以下步驟操作:
確保你的系統已安裝 inotify-tools。如果尚未安裝,可以使用以下命令進行安裝:
對于基于 Debian 的系統(如 Ubuntu):
sudo apt-get install inotify-tools
對于基于 RHEL 的系統(如 CentOS):
sudo yum install inotify-tools
創建一個名為 monitor.sh 的腳本文件,并在其中輸入以下內容:
#!/bin/bash
# 檢查參數數量
if [ $# -ne 2 ]; then
echo "Usage: $0 <directory> <event_mask>"
exit 1
fi
directory=$1
event_mask=$2
# 將事件掩碼轉換為十進制
event_mask_decimal=$(echo "0x$event_mask" | tr '[:upper:]' '[:lower:]')
# 使用 inotifywait 命令監控指定目錄的事件
inotifywait -m -r -e create -e modify -e moved_to -e deleted --format '%w%f' "$directory" | while read file; do
echo "Event detected: $file"
# 在此處添加你想要在檢測到事件時執行的命令
done
這個腳本接受兩個參數:要監控的目錄和要監控的事件掩碼。事件掩碼是一個十六進制數,表示要監控的事件類型。例如,要監控創建、修改和刪除事件,可以使用 0x00000001|0x00000002|0x00000004(即 1|2|4 的二進制表示)。
為腳本文件添加可執行權限:
chmod +x monitor.sh
運行腳本,指定要監控的目錄和事件掩碼:
./monitor.sh /path/to/directory 0x00000001|0x00000002|0x00000004
現在,monitor.sh 腳本會監控指定的目錄,并在檢測到創建、修改或刪除事件時輸出事件信息。你可以根據需要修改腳本,以便在檢測到事件時執行其他命令。