Linux 原生無回收站機制,rm -rf 一鍵毀滅系統。本文實作完整的 Bash 回收站系統:delete 替代 rm、logTrashDir 記錄元資料、restoreTrash 還原檔案,支援大檔直接刪除、7天自動清理、互動確認與絕對路徑記錄。
~/trashdelete (替代 rm)、logTrashDir (記錄)、restoreTrash (還原)/bin/ 或 /usr/local/bin/,賦予 chmod +xrealrm="/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
}
while getopts "dfiPRrvW" opt; do
case $opt in
f) exec $realrm "$@" ;; # 透傳所有參數給 rm
*) ;; # 忽略其他選項
esac
done
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
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
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"
#!/bin/bash
# 參數: newfilename original_name timestamp fullpath
echo "$1|$2|$3|$4" >> ~/.trash.log
#!/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
# 加入 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 習慣性保護