在linux下, 用rm是比较危险的, 删除了的文件不会放到所谓的回收站中, 有很多因rm而“一失足成一天恨”的例子, 下面, 我们考虑来定制一个delete命令, 并模拟做一个回收站, 这样, 即使delete文件/目录, 也会放在自建的回收站中, 相对比较安全。
用shell script来实现, delete文本文件的内容为:
#! /bin/bash
# customize a relatively safer command, namely delete, to substitute rm
# create a dustbin if necessary
if [ ! -d ~/.RecycleBin ]
then
mkdir ~/.RecycleBin
fi
# necessary, the shell script file(delete) and the file/directory to be deleted(e.g. a.txt or folder) are not necessarily in the same directory
current_dir=`pwd`
if [ $# -eq 0 ]
then
echo "Usage: delete file1 [file2 file3 ...]" # guide to use delete
else
echo "My dear, you are about to delete --- :"
echo $@
read -p "Are you sure to delete it(them)? [y/n]:" user_answer
if [ "$user_answer" == "y" ] || [ "$user_answer" == "Y" ]
then
for file in $@
do
if [ ${file:(-1)} == "/" ] # last character
then
file=${file%?} # cut the last /
fi
if [ -f "$current_dir/$file" ] || [ -d "$current_dir/$file" ]
then
# calculate the current date
current_date=`date`
current_date=${current_date// /_} # replace blank with _
dest_file="${file}__DelTime:$current_date"
mv "$current_dir/$file" "$current_dir/$dest_file"
mv "$current_dir/$dest_file" ~/.RecycleBin # move the file/directory to dustbin, not "~/.RecycleBin", but ~/.RecycleBin
else
echo "$file: No such file or directory, my dear!"
fi
done
else
echo "No file or directory removed"
fi
fi
注意, 要对文件加可执行权限。
我们查阅一下PATH的值, 并把delete这个文件放到对应的目录下(如果没有, 可以自建一个目录), 然后执行一系列的操作, 结果如下:
[taoge@localhost learn_shell]$ echo $PATH
/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:/home/taoge/bin:/home/taoge/bin
[taoge@localhost learn_shell]$ ls /home/taoge/bin/delete
/home/taoge/bin/delete
[taoge@localhost learn_shell]$ ls ~/.RecycleBin/
[taoge@localhost learn_shell]$ ls
[taoge@localhost learn_shell]$ touch a.txt; mkdir folder
[taoge@localhost learn_shell]$ delete a.txt folder
My dear, you are about to delete --- :
a.txt folder
Are you sure to delete it(them)? [y/n]:y
[taoge@localhost learn_shell]$ touch a.txt; mkdir folder
[taoge@localhost learn_shell]$ delete a.txt folder/
My dear, you are about to delete --- :
a.txt folder/
Are you sure to delete it(them)? [y/n]:y
[taoge@localhost learn_shell]$
[taoge@localhost learn_shell]$
[taoge@localhost learn_shell]$
[taoge@localhost learn_shell]$ ls -l ~/.RecycleBin/
total 8
-rw-rw-r-- 1 taoge taoge 0 May 9 22:15 a.txt__DelTime:Sat_May__9_22:16:13_PDT_2015
-rw-rw-r-- 1 taoge taoge 0 May 9 22:16 a.txt__DelTime:Sat_May__9_22:16:38_PDT_2015
drwxrwxr-x 2 taoge taoge 4096 May 9 22:15 folder__DelTime:Sat_May__9_22:16:13_PDT_2015
drwxrwxr-x 2 taoge taoge 4096 May 9 22:16 folder__DelTime:Sat_May__9_22:16:38_PDT_2015
[taoge@localhost learn_shell]$
这个~/.RecycleBin就是我们自建的回收站。 另外要注意: /home/taoge/bin的bin是binary, 是存放二进制文件的目录, 当然在本例中, 我把脚本文件放进去了, 也无妨。 .RecycleBin的bin是dustbin.
OK, 本文先介绍到这里, 上述程序基本能满足要求。 当然, 要做到非常稳健, 还是有一些地方需要改进的(比如, 如果文件或者目录中有空格, 则上述代码有错)。