萬盛學電腦網

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

Linux 以 Shell 腳本包裝 rm 指令實現「垃圾桶」機制(防誤刪可恢復)

rm 指令直接刪除檔案,**不經垃圾桶、無法恢復**,是 Linux 使用者最痛點之一。本文提供一個 Shell 腳本包裝器,攔截 rm 呼叫,將檔案移至 ~/.trash 並加上時間戳,搭配 crontab 定期清理,打造類 macOS/Windows 的垃圾桶保護機制。

rm 垃圾桶機制示意

實作步驟

1. 建立垃圾桶目錄


mkdir -p ~/.trash

2. 建立包裝腳本 ~/tools/remove.sh


#!/bin/bash
# ~/tools/remove.sh
# 用法: remove.sh file1 [file2 ...]

TRASH_DIR="$HOME/.trash"
mkdir -p "$TRASH_DIR"

for file in "$@"; do
    if [[ ! -e "$file" ]]; then
        echo "Warning: $file does not exist, skip" >&2
        continue
    fi
    timestamp=$(date +%s)
    basename=$(basename "$file")
    mv "$file" "$TRASH_DIR/${basename}.${timestamp}"
    echo "Moved: $file → $TRASH_DIR/${basename}.${timestamp}"
done

賦予執行權限:chmod +x ~/tools/remove.sh

3. 以 alias 替換 rm 指令


vim ~/.bashrc
# 末尾新增:
alias rm='sh ~/tools/remove.sh'
# 立即生效
source ~/.bashrc

4. 設定定期清理垃圾桶 (crontab)


crontab -e
# 每天凌晨 0 點清空 7 天前的檔案(保留 7 天)
0 0 * * * find ~/.trash -type f -mtime +7 -delete
# 或簡單粗暴:每天清空
# 0 0 * * * rm -rf ~/.trash/*

使用效果展示


$ rm important.txt
Moved: important.txt → /home/user/.trash/important.txt.1699900000

$ ls ~/.trash/
important.txt.1699900000

# 恢復檔案
mv ~/.trash/important.txt.1699900000 ./important.txt

進階改良建議

功能實作方向
支援 rm -r 目錄遞歸腳本中判斷 -r 參數,對目錄執行 mv
支援 rm -f 強制模式偵測 -f 參數時直接呼叫 /bin/rm -f 繞過垃圾桶
資訊列顯示垃圾桶大小整合 du -sh ~/.trash 至 PS1 提示符
圖形化恢復介面配合 zenity/yad 做 GUI 列表選擇恢復
系統級部署將腳本放 /usr/local/bin/rm-trash,/etc/profile.d/trash.sh 設定 alias

現有成熟替代方案

  • trash-cli (Python):pip install trash-cli,提供 trash-put, trash-list, trash-restore, trash-empty
  • rm-protection:pip install rm-protection,重要檔案標記保護,刪除時需回答問題
  • GNOME/KDE 桌面:原生支援 gvfs-trash / kioclient5 move trash

部署此機制後,rm 誤刪不再是災難,垃圾桶賦予你「後悔」的機會。

copyright © 萬盛學電腦網 all rights reserved