如何基于Shell脚本建立Linux回收站

  • 我们在Linux环境中工作时, 经常会用到rm命令删除文件, 但是rm命令是即刻删除的, 有时可能会出现误删的问题.
  • 针对这种情况, 本文参考网上已有解决方案, 学习并编写了一个回收站脚本.

一 工具

  • 基本功能
    1. 暂存被删除文件 rm <file/directory>
    2. 恢复被删除文件 re <file/directory>
    3. 清空回收站 rc
    4. 获取回收站大小 rsize

初始化与安装

  1. github, https://github.com/trioZwShen/itrashcan.git
  2. ~/.bashrc中粘贴下面的设置环境变量, 并执行source ~/.bashrc, 或者重新打开终端
    # itrashcan
    export itrashcan="/home/szw/repos/itrashcan" # set the script path
    export itrashcan_home="/home/szw/.trashcan" # set the transcan path
    source "$itrashcan/config.sh" # source the config for alias
    
  3. 初始化itrashcan
    bash $itrashcan/init.sh
    
  4. 查看config.sh中的命令别名
    # set alias
    # rm by itrashcan
    alias rm="$itrashcan/delete.sh"
    # clear the trashcan
    alias rc="$itrashcan/clear.sh"
    # restore the target
    alias re="$itrashcan/restore.sh"
    # go to the trashcan
    alias gor="cd $itrashcan_home/trash"
    # get the size of trashcan
    alias rsize="du -sh $itrashcan_home/trash"
    
  5. 删除回收站
    • bash remove.sh

测试

  • rm
$ ls
a  b  c
$ rm *
/home/szw/download/a is move to trashcan
/home/szw/download/b is move to trashcan
/home/szw/download/c is move to trashcan
  • re
$ re a b
/home/szw/download/a restored
/home/szw/download/b restored
  • rc
$ rc
Are you sure you want to permanently erase the items in the Trash?[Y/n]
Y
Done!
  • rsize
$ rsize
4.0K    /home/szw/.trashcan/trash


二 功能实现

1 环境初始化

环境变量

# itrashcan
export itrashcan="/home/szw/repos/itrashcan" # set the script path
export itrashcan_home="/home/szw/.trashcan" # set the transcan path
source "$itrashcan/config.sh" # source the config for alias
  • itrashcan设置为脚本所在路径
  • itrashcan_home设置为回收站的目标位置, 回收站名称可以自拟
  • config.sh中包含了itrashcan的命令别名

脚本

  • init.sh 执行前需设置环境变量
    1. 检查环境变量是否被设置
    2. 检查回收站目标位置是否有冲突
    3. 创建回收站
    4. 初始化脚本以及回收站的权限
#!/bin/bash
# run this script for init your environment
# set -x
set -e

# check the $itrashcan_home.
if [ ! -n "$itrashcan_home" ]; then
    echo "Please set the environment var first!!!"
    exit
fi

# exit if the $itrashcan_home already exists.
if [ -d "$itrashcan_home" ]; then
    echo "The directory already exists in the target path, please check!!!"
    exit
fi

# create trashcan and trash log
mkdir $itrashcan_home
mkdir $itrashcan_home"/trash"
touch $itrashcan_home"/trash.log"

# init permissions
chmod 777 -R $itrashcan_home
chmod 755 -R $itrashcan

echo "Init Done."
  • remove.sh
    • 删除回收站
#!/bash/bin
# run this script for remove itrashcan config and environmental
# set -x
set -e
# clear file and directory
/bin/rm -rf $itrashcan_home
echo "Remove done."

2 删除文件

delete.sh

  1. 该脚本首先会检查环境是否已经初始化, 没有则init
    # init if the $itrashcan_home not exists
    if [ ! -d "$itrashcan_home" ]; then
        bash init.sh
    fi
    
  2. 检查输入是否正确, 如果-f选项, 那么使用real rm
  3. 利用lldu判断目标文件是否大于2G, 如果大于2G, 则会直接删除
  4. 重命名回收站中的文件为filename_deletetime, 防止文件重名
  5. 获取文件的绝对路径, 用于恢复回收站文件
  6. 移动文件, 并打log
#!/bin/bash
# set -x
set -e
realrm="/bin/rm"

# init if the $itrashcan_home not exists
if [ ! -d "$itrashcan_home" ]; then
    bash init.sh
fi

# usage tips
if [ $# -eq 0 ]; then
    echo "Usage:delete file [file2 file3 ...]"
    echo "If the options contain -f then the script will exec 'rm' directly."
fi

# identify input options, if f is point then exec realrm
while getopts "dfiPRrvw" opt
do
    case $opt in
    f)
        echo "real rm done"
        exec $realrm "$@"
        ;;
    d)
        # do nothing
        ;;
    i)
        # do nothing
        ;;
    P)
        # do nothing
        ;;
    R)
        # do nothing
        ;;
    r)
        # do nothing
        ;;
    v)
        # do nothing
        ;;
    w)
        # do nothing
        ;;
    ?) # unknow argument
        exit
        ;;
    esac
done

# travel the input file
for file in $@
do
    if [ -f "$file" -o -d "$file" ]; then
        # real rm if size is larger than 2G
        if [ -f "$file" ] && [ `ls -l $file|awk '{print $5}'` -gt 2147483648 ]
        then
            echo "$file size is lager than 2G, will be deleted directly"
            rm -rf $file
        fi
        if [ -d "$file" ] && [ `du -sb $file|awk '{print $1}'` -gt 2147483648 ]
        then
            echo "The directory: $file size is lager than 2G, will be deleted directly"
            rm -rf $file
        fi

        # rename
        now=`date +%Y-%m-%d_%H_%M_%S`
        filename=`basename $file`
        newfilename="${filename}_${now}"

        # get fullpath
        basepath=$(cd `dirname $file`; pwd)
        fullpath="${basepath}/${filename}"

        # mv to trashcan
        if mv -f "$fullpath" "$itrashcan_home/trash/$newfilename"
        then
            bash $itrashcan/log.sh $newfilename $filename $now $fullpath
            echo "$fullpath is move to trashcan"
        else
            echo "fail"
        fi

    else
        echo "$file is not exist"
    fi
done

# trashcan size > 10G remider user
if [ `du -sb "${itrashcan_home}"/trash|awk '{print $1}'` -gt 5368709120 ]; then
    echo "Warning: trashcan's size[`du -sh "${itrashcan_home}/trash"|awk '{print $1}'`] is biger than 5G."
fi

3 恢复数据

restore.sh

  1. 检查输入
  2. 设置log路径, 回收站路径, 以及待查找的目标模式findpattern
  3. 在log中查找目标文件, 获取同名文件数rowcount;
    • 如果有多个重名文件, 需要用户自己确定恢复哪个
  4. 检查回收站中该文件是否存在
  5. 检查原路径是否存在, 检查原路径中是否有重名文件
  6. 恢复数据, 并删除该记录
#!/bin/bash
set -e
if [ $# -eq 0 ]; then
    echo "Please enther the target what your want to restore!";
    exit;
fi

# travel the input file
for target in $@
do
    log="${itrashcan_home}/trash.log"
    trashcan="${itrashcan_home}/trash"
    findpattern="filename:${target};"

    # get the number of files with the same name
    rowcount=`cat -n "$log" | grep "$findpattern" | wc -l`

    if [ $rowcount -eq 0 ]; then
        echo "${target} does not exists in LOG"
        exit

    elif [ $rowcount -eq 1 ]; then
        output=`cat -n "$log" | grep "$findpattern"`
        index=`echo $output | awk '{print $1}'`

    else
        cat -n "${itrashcan_home}/trash.log" | grep "${findpattern}"
        echo -n "Please enter the line number of the target: "
        read index
        output=`cat -n "$log" | grep "\ ${index}\ *.*${findpattern}.*"`
    fi

    # get the fullpath and trashname by index
    fullpath=`echo $output | awk '{print $5}'`
    fullpath=${fullpath#*:}
    trashname=`echo $output | awk '{print $2}'`
    trashname=${trashname#*:}

    # check the trashname
    trashnamepath="${trashcan}/${trashname}"
    if [ ! -d "$trashnamepath" -a ! -f "$trashnamepath" ]; then
        echo "${target} does not exists in TRASHCAN"
        exit
    fi
    # Whether the original path exists.
    basepath=`dirname $fullpath`
    if [ ! -d $basepath ]; then
        echo "The original path [${basepath}] does not exist!!!"
        exit
    fi
    # Is there a duplicate file under the original path?
    if [ -d $fullpath -o -f $fullpath ]; then
        echo "The original path has a duplicate file [$fullpath]!!!"
        exit
    fi

    # restore from trashcan
    if ! mv -f "$trashnamepath" "$fullpath"; then
        echo "failed"
        exit
    else
        # delete the log
        sed -i "${index}d" $log
        echo "${fullpath} restored"
    fi
done

4 log

log.sh

  • 需记录原文件名, 重命名后的文件名, 源文件所在路径
#!/bin/bash
log="${itrashcan_home}/trash.log"
# create log file if log does not exist
if [ ! -d $log ]; then
    touch $log
fi
echo "trashname:$1 filename:$2; deletetime:$3 fullpath:$4" >> $log

5 清空回收站

clear.sh

#!/bin/bash
echo "Are you sure you want to permanently erase the items in the Trash?[Y/n]"
read ask
if [ $ask = 'y' -o $ask = 'Y' ]
then
    `rm -rf $itrashcan_home/trash/*`
    `rm -rf $itrashcan_home/trash.log`
    echo "Done!"
fi

参考blog
https://www.jianshu.com/writer#/notebooks/27796113/notes/42433921/preview

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 162,050评论 4 370
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,538评论 1 306
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 111,673评论 0 254
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,622评论 0 218
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 53,047评论 3 295
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,974评论 1 224
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,129评论 2 317
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,893评论 0 209
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,654评论 1 250
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,828评论 2 254
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,297评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,619评论 3 262
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,326评论 3 243
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,176评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,975评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,118评论 2 285
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,909评论 2 278

推荐阅读更多精彩内容