Linux 回收站——防止误删文件

发布时间 2023-04-24 01:08:16作者: 凌晗

方法 1:bash 脚本(写入~/.bashrc 文件),简单实用无外部依赖

提供如下四个命令:

rmv a <b c>:move a <b and c> to recycle bin
unrmv a <b>: restore a from recycle bin to <b> (default b='./') 
lsrmv: list recycle bin
clearrmv: clear recycle bin
# >>> recycle bin >>>
## define trash dir and make it
# trash_path="~/.trash"
# trash_path="$HOME/.trash"
trash_path="/hhd/2/zzh/.trash/" # # assign one according to your need
# make the $trash_path dir if there is no one.
if [ ! -d $trash_path ]; then
    mkdir -p $trash_path
fi

## define alias
alias rmv=trash # rmv a <b c>:move a <b and c> to recycle bin
alias unrmv=restorefile  # unrmv a <b>: restore a from recycle bin to <b> (default b='./') 
alias lsrmv=lstrash # lsrmv: list recycle bin
alias clearrmv=cleartrash # clearrmv: clear recycle bin

## functions 
# move to recycle bin
trash()
{   if [[ $# -le 0 ]]; then
    	echo "please assign the parameters: delete_file"
    	return
    fi
    
    for i in $*; do
      STAMP=`date "+%Y-%m-%d"`
      file_srcpath=`echo $i | sed 's/\(.*\)\/$/\1/g'`
      file_dstpath=$trash_path/$STAMP/$file_srcpath
      
      if [ -e $file_dstpath ];then
          suffix=`date "+%Y%m%d%H%M%S"`
          file_dstpath=${file_dstpath}_${suffix}
      fi
      
      file_path_dir=`dirname $file_dstpath`
      mkdir -p $file_path_dir
      mv $file_srcpath  $file_dstpath
    done
}
 
# restore from recycle bin
restorefile()
{
    if [[ $# -eq 1 ]]; then
      restore_file=$1
    	restore_path="./"  # default restore path = ./
    elif [[ $# -eq 2 ]]; then
      restore_file=$1
    	restore_path=$2  # default restore path = ./
    else
    	echo "please assign the parameters: restore_file <restore_dir>"
    	return
    fi
    
    mv -i $trash_path/$restore_file $restore_path
}

 

# show recycle bin contents 
lstrash()
{
  # files=`find $trash_path -type f`
  dirs=`find $trash_path -maxdepth 2 -mindepth 2 -type d`
  files=`find $trash_path -maxdepth 2 -type f`
  printf "\n------ Dirs ------\n"
  while read -r line; do
      echo "${line/$trash_path/}"
  done <<< "$dirs"
  printf "\n------ Files ------\n"
  while read -r line; do
      echo "${line/$trash_path/}"
  done <<< "$files"
}

# clear recycle bin
cleartrash()
{
    read -p "Sure to clear the trash box?[y/n]" confirm
    [ $confirm == 'y' ] || [ $confirm == 'Y' ]  && /bin/rm -rdf  $trash_path/*
}

# <<< recycle bin <<<

如果需要定期清理回收站,可以使用 Linux 的定时任务命令 crontab 定期删除 trash 目录,但是不建议这么做,因为 rm 命令有风险(惨痛教训!),还是自己需要的时候手动运行命令 clearrmv 清理回收站比较好。

方法 2:开源命令行工具,功能更全面

GitHub - andreafrancia/trash-cli: Command line interface to the freedesktop.org trashcan.