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

mkdir -p ~/.trash
~/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
vim ~/.bashrc
# 末尾新增:
alias rm='sh ~/tools/remove.sh'
# 立即生效
source ~/.bashrc
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 |
pip install trash-cli,提供 trash-put, trash-list, trash-restore, trash-emptypip install rm-protection,重要檔案標記保護,刪除時需回答問題gvfs-trash / kioclient5 move trash部署此機制後,rm 誤刪不再是災難,垃圾桶賦予你「後悔」的機會。