shell脚本来实现类似回收站功能

背景:
工作中,总会有人聊到曾经做过的最坑的事情,其中当然少不了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

#!/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

 

你可能感兴趣的:(Linux)