Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 打造 rm 指令回收站機制,防誤刪救命神技

編輯:Linux 教學

前言

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 關鍵字略過別名

五、自動清理超過 N 天的檔案(排程)

# /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 操作習慣,讓誤刪不再是災難。

Copyright © Windows教程網 All Rights Reserved