当前位置: > Linux命令 >

给rm命令加上回收站功能

时间:2016-06-04 17:14来源:linux.it.net.cn 作者:IT

背景:
在群里,总会有人聊到曾经做过的最坑的事情,其中当然少不了rm命令,比如最出名的rm -rf /*命令。
受HDFS回收站机制的启发,我即兴的写了一个shell脚本来实现类似的功能。

具体配置:
[dong@localhost ~]$ sudo touch /usr/bin/delete
[dong@localhost ~]$ sudo chmod +x /usr/bin/delete
[dong@localhost ~]$ sudo vim /usr/bin/delete

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#!/bin/bash
 
trash_dir=${HOME}/.Trash/$(date +%Y%m%d%H%M%S)
 
function move_item(){
  item=$1
  full_path=$2
  full_dir=$(dirname ${full_path})
  mkdir -p ${trash_dir}${full_dir}
  mv ${item} ${trash_dir}${full_path}
  if [[ $? -eq 0 ]]; then
    echo "Moved ${item} to ${trash_dir}${full_path}"
  fi
}
 
if [[ $# -eq 0 ]] || $(echo "$1" |grep -Ewq '\-h|\-\-help'); then
  echo "${0} [-f] [*|FILE]"
  exit 2
fi
 
for item in $@; do
  if $(echo ${item} |grep -vq '^-'); then
    if $(echo ${item} |grep -q '^/'); then
      full_path=${item}
    else
      full_path=$(pwd)/${item}
    fi
    if $(echo $@ |grep -Ewq '\-f|\-rf|\-fr'); then
      move_item ${item} ${full_path}
    else
      echo -n "Move ${item} to ${trash_dir}${full_path}? [y/n] "
      read yorn
      if $(echo ${yorn} |grep -Ewq 'y|Y|yes|YES'); then
        move_item ${item} ${full_path}
      fi
    fi
  fi
done

 

[dong@localhost ~]$ mkdir tmp
[dong@localhost ~]$ cd tmp
[dong@localhost tmp]$ mkdir 1 2 3
[dong@localhost tmp]$ echo 1 > 1/1.txt
[dong@localhost tmp]$ echo 2 > 2/2.txt
[dong@localhost tmp]$ echo 3 > 3/3.txt
[dong@localhost tmp]$ touch a b c
[dong@localhost tmp]$ ln -s a d
[dong@localhost tmp]$ delete 1

Move 1 to /home/dong/.Trash/20160415114210/home/dong/tmp/1? [y/n] y
Moved 1 to /home/dong/.Trash/20160415114210/home/dong/tmp/1

[dong@localhost tmp]$ delete -f *

Moved 2 to /home/dong/.Trash/20160415114217/home/dong/tmp/2
Moved 3 to /home/dong/.Trash/20160415114217/home/dong/tmp/3
Moved a to /home/dong/.Trash/20160415114217/home/dong/tmp/a
Moved b to /home/dong/.Trash/20160415114217/home/dong/tmp/b
Moved c to /home/dong/.Trash/20160415114217/home/dong/tmp/c
Moved d to /home/dong/.Trash/20160415114217/home/dong/tmp/d



(责任编辑:IT)
------分隔线----------------------------
栏目列表
推荐内容