inotify 是 Linux 內核提供的一種文件系統事件監控機制,可以用來監控文件或目錄的變化,如創建、刪除、修改等。在 Debian 系統中,你可以使用 inotify-tools 包來方便地使用 inotify。
以下是在 Debian 中配置和使用 inotify 的步驟:
sudo apt update
inotify-tools:sudo apt install inotify-tools
安裝完成后,你可以使用 inotifywait 和 inotifywatch 命令來監控文件系統事件。
inotifywait 用于實時監控文件或目錄的變化,并在檢測到事件時輸出相關信息。
示例用法:
inotifywait -m /path/to/directory -e create,delete,modify
-m:持續監控,直到手動終止。/path/to/directory:要監控的目錄路徑。-e:指定要監控的事件類型,如 create(創建)、delete(刪除)、modify(修改)等。你可以根據需要添加更多事件類型,例如 move(移動)、attrib(屬性變化)等。
inotifywatch 用于統計一段時間內文件系統事件的發生次數。
示例用法:
inotifywatch -t 60 -e create,delete,modify /path/to/directory
-t:指定監控的總時間(秒)。inotifywait 類似。假設你想監控 /home/user/documents 目錄下的所有文件和子目錄,當有文件被創建、刪除或修改時,輸出相關信息。你可以創建一個簡單的 shell 腳本來實現這個功能:
#!/bin/bash
MONITOR_DIR="/home/user/documents"
EVENTS="create,delete,modify"
inotifywait -m -r -e "$EVENTS" "$MONITOR_DIR" |
while read path action file; do
echo "The file '$file' appeared in directory '$path' via '$action'"
done
保存這個腳本為 monitor.sh,然后賦予執行權限并運行:
chmod +x monitor.sh
./monitor.sh
這樣,你就可以實時監控 /home/user/documents 目錄下的文件變化了。
inotify 有文件描述符的限制,如果監控的文件或目錄非常多,可能會達到限制??梢酝ㄟ^調整內核參數來增加限制:echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p
inotifywait 和 inotifywatch 是阻塞式的,如果你需要在后臺運行,可以考慮使用 nohup 或 & 將其放入后臺。通過以上步驟,你可以在 Debian 系統中方便地配置和使用 inotify 來監控文件系統的變化。