萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

Linux 實作類 Windows 回收站功能:Bash 腳本實現安全刪除、自動清理與還原

Linux 原生無回收站機制,rm -rf 一鍵毀滅系統。本文實作完整的 Bash 回收站系統:delete 替代 rm、logTrashDir 記錄元資料、restoreTrash 還原檔案,支援大檔直接刪除、7天自動清理、互動確認與絕對路徑記錄。

架構設計

  • 回收站目錄:~/trash
  • 核心腳本:delete (替代 rm)、logTrashDir (記錄)、restoreTrash (還原)
  • 部署位置:/bin/ 或 /usr/local/bin/,賦予 chmod +x

delete 核心腳本邏輯

1. 初始化與說明

realrm="/bin/rm"
[ ! -d ~/trash ] && { mkdir -v ~/trash; chmod 777 ~/trash; }

[ $# -eq 0 ] && {
  echo "Usage: delete file1 [file2 file3...]"
  echo "Options containing -f will execute rm directly"
  exit 1
}

2. -f 選項直通 rm (繞過回收站)

while getopts "dfiPRrvW" opt; do
  case $opt in
    f) exec $realrm "$@" ;;  # 透傳所有參數給 rm
    *) ;;  # 忽略其他選項
  esac
done

3. 互動確認

echo -ne "Are you sure you want to move the files to the trash? [Y/N]: \a"
read reply
[ "$reply" != "y" ] && [ "$reply" != "Y" ] && exit 1

4. 大檔/目錄直接刪除 (>2GB)

for file in "$@"; do
  if [ -f "$file" ] || [ -d "$file" ]; then
    if [ -f "$file" ] && [ $(ls -l "$file" | awk '{print $5}') -gt 2147483648 ]; then
      echo "$file size > 2GB, deleting directly"
      $realrm -rf "$file"
      continue
    fi
    if [ -d "$file" ] && [ $(du -sb "$file" | awk '{print $1}') -gt 2147483648 ]; then
      echo "Directory $file > 2GB, deleting directly"
      $realrm -rf "$file"
      continue
    fi
    # ... 移至回收站邏輯
  fi
done

5. 移至回收站並記錄

now=$(date +%Y%m%d_%H_%M_%S)
filename="${file##*/}"
newfilename="${filename}_${now}"

# 解析絕對路徑
if [ "$file" = "${file//\//}" ]; then          # 純檔名
  fullpath="$(pwd)/$file"
elif [ "$file" != "${file//./}" ]; then        # 含 ./ 相對路徑
  fullpath="$(pwd)${file#.}"
else                                            # 絕對路徑
  fullpath="$file"
fi

mv -f "$file" ~/trash/"$newfilename" && \
  logTrashDir "$newfilename $filename $now $fullpath" && \
  echo "File $file moved to trash" || \
  echo "Operation failed"

logTrashDir 記錄腳本

#!/bin/bash
# 參數: newfilename original_name timestamp fullpath
echo "$1|$2|$3|$4" >> ~/.trash.log

restoreTrash 還原腳本

#!/bin/bash
# 使用方式: restoreTrash "檔案名稱關鍵字"
grep "$1" ~/.trash.log | while IFS='|' read newname orig time path; do
  if [ -f ~/trash/"$newname" ]; then
    mkdir -p "$(dirname "$path")"
    mv ~/trash/"$newname" "$path"
    echo "Restored: $path"
  fi
done

自動清理:7天超過自動刪除

# 加入 crontab 每天執行
find ~/trash -type f -mtime +7 -delete
# 或清理空目錄
find ~/trash -type d -empty -delete

使用方式

# 刪除檔案 (互動確認)
delete 重要文件.txt 專案目錄/

# 強制直接刪除 (繞過回收站)
delete -rf 暫存目錄/

# 還原檔案
restoreTrash "重要文件"

# 查看回收站內容
ls -lh ~/trash

限制與改進方向

  • 不支援跨檔案系統移動 (需改用 cp + rm)
  • 無圖形介面,純命令列操作
  • 可整合 trash-cli (FreeDesktop.org 標準) 獲得桌面環境整合
  • 建議加入 alias rm='delete' 至 ~/.bashrc 習慣性保護
copyright © 萬盛學電腦網 all rights reserved