在 CentOS 上,可以使用 inotify 工具來實現實時監控文件
sudo yum install inotify-tools
monitor.sh
的腳本文件,并在其中添加以下內容:#!/bin/bash
# 檢查參數數量
if [ $# -ne 1 ]; then
echo "Usage: $0 <directory>"
exit 1
fi
directory=$1
# 使用 inotifywait 命令監控指定目錄
inotifywait -m -r -e create -e modify -e delete --format '%w%f' "$directory" | while read file; do
echo "File: $file"
# 在這里執行您需要的操作,例如備份文件、發送通知等
done
這個腳本接受一個參數,即要監控的目錄。它會使用 inotifywait
命令實時監控該目錄中的文件創建、修改和刪除事件。當發生這些事件時,腳本會輸出文件名,并可以執行其他操作,例如備份文件或發送通知。
chmod +x monitor.sh
./monitor.sh /path/to/directory
現在,腳本會實時監控指定的目錄,并在發生文件創建、修改或刪除事件時輸出文件名。您可以根據需要修改腳本以執行其他操作。