rm 指令十分的危险… 为此希望实现一个回收站. archwiki给出了一些可用的建议 Trash management, 用下来体验不好, 打算自己搞一个.
第一版的trash自己解析了输入的参数.. 然后加上unix时间戳后mv到一个指定的公共磁盘分区上(因而其实性能也不太好, 尤其是大文件的删除时), 但是最后还是死在了处理空格和引号之类的问题上.. 而且与原生rm的兼容性不好…
目前直接使用mv
指令, 不再自己解析过多的参数了, 直接把参数喂给mv
, 这样就不用自己考虑空格和引号的问题了. 也不加时间戳了, 重名文件直接"覆盖"掉.(先rm掉旧的, 再mv进去, 因为mv好像不能自动的覆盖文件夹, 所以rm了算了)
sh
1#!/bin/sh
2
3DEST="/home/`whoami`/.trash/"
4
5# No arguments...
6if [ -z "$1" ]; then
7 echo "trash: trash [FILE]..."
8 exit -1;
9fi
10
11
12for file in "$@"; do
13 filename=${file##*/}
14
15 if [ ! -e $file -a ! -L $file ]; then
16 echo -e "\033[31m[Error]\033[0m No such file or directory '$file'"
17 continue
18 fi
19
20 if [ ! -e $DEST$filename -a ! -L $DEST$filename ]; then
21 mv "$file" $DEST
22 continue
23 fi
24
25 echo -ne "\033[35m[Warning]\033[0m File or directory '$DEST$filename' exists! Override? (y/n) "
26 read answer
27 if [ -z "$answer" -o "${answer:0:1}x" = 'yx' -o "${answer:0:1}" = 'Yx' ]; then
28 rm -rf $DEST$filename
29 mv "$file" $DEST
30 echo -e "\033[32m[Success]\033[0m Removed $DEST$filename."
31 fi
32done
以及trashctl管理工具:
sh
1#!/bin/sh
2
3DEST="/home/`whoami`/.trash/"
4
5if [ -z "$1" ]; then
6 echo "trashctl: [ list | empty ]"
7 exit -1
8fi
9
10if [ $1 = 'list' -o $1 = 'lis' -o $1 = 'li' -o $1 = 'l' -o $1 = 'ls' ]; then
11 ls -al --color=auto $DEST
12 echo '-----------------------------------'
13 echo -e 'Disk Usage: \c'
14 du -sh $DEST
15
16
17elif [ $1 = 'empty' -o $1 = 'empy' -o $1 = 'emp' -o $1 = 'em' -o $1 = 'e' ]; then
18 echo -ne "\033[31m[Warning]\033[0m Remove all files in '$DEST'? (y/n) "
19 read answer
20 if [ -z "$answer" -o "${answer:0:1}x" = 'yx' -o "${answer:0:1}" = 'Yx' ]; then
21 rm -rf $DEST*
22 echo -e '\033[32m[Success]\033[0m Removed.'
23 fi
24else
25 echo "trashctl: [ list | empty ]"
26 exit -1
27fi
28
29exit 0