inotify
是 Linux 系統中的一個功能,它可以監控文件系統事件,如文件的創建、修改、刪除等。通過使用 inotify
,我們可以在文件被刪除或修改之前采取行動,從而防止文件丟失。以下是如何利用 inotify
防止文件丟失的方法:
首先,你需要安裝 inotify-tools
,這是一個常用的 inotify
工具集。
sudo apt-get update
sudo apt-get install inotify-tools
inotifywait
是 inotify-tools
中的一個命令行工具,可以用來監控文件系統事件。
inotifywait -m /path/to/your/file -e modify,attrib,close_write,move,create,delete
這個命令會持續監控指定文件的修改、屬性變化、關閉寫入、移動、創建和刪除事件。
如果你想監控一個目錄及其子目錄中的所有文件,可以使用 -r
選項:
inotifywait -m -r /path/to/your/directory -e modify,attrib,close_write,move,create,delete
你可以編寫一個簡單的腳本來自動備份被修改或刪除的文件。
#!/bin/bash
MONITOR_DIR="/path/to/your/directory"
BACKUP_DIR="/path/to/your/backup"
# 創建備份目錄(如果不存在)
mkdir -p "$BACKUP_DIR"
inotifywait -m -r "$MONITOR_DIR" -e modify,attrib,close_write,move,create,delete |
while read -r directory events filename; do
# 構建文件的完整路徑
file_path="$directory/$filename"
# 根據事件類型采取行動
case $events in
modify|attrib|close_write)
# 文件被修改或關閉寫入,進行備份
cp "$file_path" "$BACKUP_DIR/$(basename "$file_path")"
echo "Backup created for $file_path"
;;
move|create)
# 文件被移動或創建,進行備份
cp "$file_path" "$BACKUP_DIR/$(basename "$file_path")"
echo "Backup created for $file_path"
;;
delete)
# 文件被刪除,進行備份(如果文件在備份目錄中存在)
if [ -f "$BACKUP_DIR/$(basename "$file_path")" ]; then
cp "$BACKUP_DIR/$(basename "$file_path")" "$BACKUP_DIR/$(basename "$file_path")_deleted"
echo "Deleted file backed up as $(basename "$file_path")_deleted"
fi
;;
esac
done
將上述腳本保存為一個文件,例如 backup_script.sh
,然后賦予執行權限并運行:
chmod +x backup_script.sh
./backup_script.sh
通過上述方法,你可以利用 inotify
監控文件系統事件,并在文件被修改、刪除或移動時自動進行備份,從而有效防止文件丟失。