记录跟随互联网发展的每一步

可以与 safe-rm 协同工作的 bash 回收站

将以代码放进 ~/.bashrc,并执行 source ~/.bashrc 命令即可开始使用

该脚本在用户目录下建立 .delete 文件夹作为回收站,并替换 rm 命令为 toBackup 方法,将删除文件的动作替换为把文件移动至 .delete/删除日期 并重命名为 删除时间-文件名-随机数 的格式

lsdel 用于查看今天删除了哪些文件

cleandel 用于清除回收站

# for rm {{

DEL_TIME=$(date +%H%M%S)
BAK_DATE=$(date +%Y%m%d)
RANDOM=$(date +%s%N | cut -c 6-13)

checkDelDir ()
{
    if [ ! -d ~/.delete ]; then
        mkdir ~/.delete
    fi

    if [ ! -d ~/.delete/${BAK_DATE} ]; then
        mkdir ~/.delete/${BAK_DATE}
    fi
}

toBackup()
{
    checkDelDir
    for thing in $@
    do
        echo ${thing} | grep '^-' > /dev/null
        if [ ! $? = 0 ]; then
            thing_name=${thing##*/}
            rnd=${RANDOM}
            mv ${thing} ~/.delete/${BAK_DATE}/${DEL_TIME}-${thing_name%*/}-${rnd}
            echo rename ${thing} to ${DEL_TIME}-${thing_name%*/}-${rnd} and mv to ~/.delete/${BAK_DATE}
        fi
    done
}

cleanDelete()
{
    echo 'Clear all backup files?[Y/N]'
    read confirm
    if [[ ${confirm} = 'y' || ${confirm} = 'Y' ]]; then
        /bin/rm -rf ~/.delete/*
    elif [[ ${confirm} = 'n' || ${confirm} = 'N' ]]; then
        echo 'Delete is cancelled by user.'
    else
        echo 'Delete is cancelled because user not press anything.Press y or Y to confirm delete.'
    fi
}

listDelete()
{
    echo 'ls ~/.delete/${BAK_DATE}'
    echo 'Only list what you delete today.'
    echo
    ls ~/.delete/${BAK_DATE}
}

alias rm=toBackup
alias lsdel=listDelete
alias cleandel=cleanDelete

# }}

以下脚本配合 safe-rm 使用

/usr/bin 目录下创建 bashrc-rm 文件,并赋予执行权限

touch /usr/bin
chmod +x /usr/bin/bashrc-rm

将以下代码写进 bashrc-rm

#!/bin/bash
date=/bin/date
cut=/usr/bin/cut
mkdir=/bin/mkdir
echo=/bin/echo
mv=/bin/mv
grep=/bin/grep
DEL_TIME=$(${date} +%H%M%S)
BAK_DATE=$(${date} +%Y%m%d)
RANDOM=$(${date} +%s%N | ${cut} -c 6-13)

checkDelDir ()
{
    if [ ! -d ~/.delete ]; then
        ${mkdir} ~/.delete
    fi

    if [ ! -d ~/.delete/${BAK_DATE} ]; then
        ${mkdir} ~/.delete/${BAK_DATE}
    fi
}

toBackup()
{
    checkDelDir
    for thing in $@
    do
        ${echo} ${thing} | ${grep} '^-' > /dev/null
        if [ ! $? = 0 ]; then
            thing_name=${thing##*/}
            rnd=${RANDOM}
            ${mv} ${thing} ~/.delete/${BAK_DATE}/${DEL_TIME}-${thing_name%*/}-${rnd}
            ${echo} rename ${thing} to ${DEL_TIME}-${thing_name%*/}-${rnd} and mv to ~/.delete/${BAK_DATE}
        fi
    done
}

toBackup $*

替换 safe-rm 脚本中执行删除操作时调用的命令

该变量在 safe-rm 0.12 版本中定义于 107 行附近

my $real_rm = '/bin/rm';
替换为
my $real_rm = '/usr/bin/bashrc-rm';

删除 ~/.bashrctoBackupcheckDelDir 两个函数,并替换之前的别名定义

alias rm=toBackup
替换为
alias rm=/usr/bin/safe-rm

点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注