较安全的rm脚本

想必不少人体会过在Linux下误删文件的欲哭无泪的感觉。我整理出一份比较安全的rm脚本,贴在这里。

特性

  • 接管原生的/bin/rm命令,将待删除的文件mv至回收站,便于统一管理,或者更重要的,拯救误删文件。
  • 需要调用原生的rm时,指定路径即可,例如:/bin/rm -rf somefolder
  • 记录删除日志到/var/log/trash.log。如果不需要记录日志,只需要将log变量置空即可。
  • 将文件移动至回收站时自动重命名,以便可以重复删除重名文件。
  • 贴图:我爱正则表达式

贴代码

用法

  • 将下面的代码贴至~/.bashrc 或 ~/.bash_profile中,然后刷新该文件source ~/.bashrc即可。
  • 临时取消自定义的rm:可以使用前文所说的/bin/rm或在当前环境下取消该function的定义:unset -f rm
  • 需要根据自己的系统,修改一下各个变量的定义。
  • 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
    #safe remove, mv the files to .Trash with unique name
    #and log the acction
    function rm()
    {
        trash="$HOME/.Trash"
        log="/var/log/trash.log"
        stamp=`date "+%Y-%m-%d %H:%M:%S"` #current time

        while [ -f "$1" ]; do

            #remove the possible ending /
            file=`echo $1 |sed 's#\/$##' `

            pure_filename=`echo $file  |awk -F / '{print $NF}' |sed -e "s#^\.##" `

            if [ `echo $pure_filename | grep "\." ` ]; then
                new_file=` echo $pure_filename |sed -e "s/\([^.]*$\)/$RANDOM.\1/" `
            else
                new_file="$pure_filename.$RANDOM"
            fi

            trash_file="$trash/$new_file"
            mv "$file" "$trash_file"

            if [ -w $log ]; then
                echo -e "[$stamp]\t$file\t=>\t[$trash_file]" |tee -a $log
            else
                echo -e "[$stamp]\t$file\t=>\t[$trash_file]"
            fi

            shift   #increment the loop
        done
    }
    原文地址:https://www.cnblogs.com/shihao/p/2315494.html