Linux 下 rm -rf 一聲令下,檔案直接從 inode 釋放,想救回來得靠 extundelete 或 debugfs 逐區塊掃描,且檔名通常變成無意義的 inode 編號。本文提供一套純 Shell 函式實作的「回收站」機制,透過別名攔截 rm,將刪除動作轉為移動至 ~/.trash,並支援還原、列表、清空等操作,極大降低誤刪風險。
~/.bashrc 或 /etc/profile)# 建立回收站目錄
mkdir -p ~/.trash
# 別名攔截
alias rm=trash
alias r=trash
alias rl='ls -lh ~/.trash'
alias ur=undelfile
# 還原函式:互動式移回當前目錄
undelfile() {
mv -i ~/.trash/"$@" ./
}
# 刪除函式:移動至回收站
trash() {
mv "$@" ~/.trash/
}
# 清空回收站:雙重確認
cleartrash() {
read -p "clear sure? [n] " confirm
[[ $confirm == [yY] ]] && /bin/rm -rf ~/.trash/*
}
套用設定:source ~/.bashrc
$ rm important.doc # 實際執行 mv important.doc ~/.trash/
$ rl # 列出回收站內容
$ ur important.doc # 還原至當前目錄
$ cleartrash # 清空回收站(需輸入 y 確認)
將上述內容寫入 /etc/profile 並 source /etc/profile,新建使用者登入時自動擁有回收站功能。
/bin/rm -rf 真要刪除的檔案 # 使用絕對路徑呼叫原生 rm
command rm -rf 真要刪除的檔案 # 或用 command 關鍵字略過別名
# /etc/cron.daily/clean-trash
#!/bin/bash
find /home/*/.trash -type f -mtime +7 -delete
find /root/.trash -type f -mtime +7 -delete
給予執行權限:chmod +x /etc/cron.daily/clean-trash
mv 會退化為「複製+刪除」,大檔案會較慢。trash() 中加入時間戳重命名邏輯。rm -r 目錄 會整個目錄移入,還原時需注意相對路徑。rm -f 的強制語意(本機制本身即為安全優先)。幾行 Shell 函式即可為 Linux 建立類 Windows 回收站的保護層,配合 cron 定期清理,兼顧安全與磁碟空間。團隊環境建議部署至 /etc/profile 統一管理,養成 rl、ur 操作習慣,讓誤刪不再是災難。