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

  • 我們在Linux環(huán)境中工作時, 經(jīng)常會用到rm命令刪除文件, 但是rm命令是即刻刪除的, 有時可能會出現(xiàn)誤刪的問題.
  • 針對這種情況, 本文參考網(wǎng)上已有解決方案, 學(xué)習(xí)并編寫了一個回收站腳本.

一 工具

  • 基本功能
    1. 暫存被刪除文件 rm <file/directory>
    2. 恢復(fù)被刪除文件 re <file/directory>
    3. 清空回收站 rc
    4. 獲取回收站大小 rsize

初始化與安裝

  1. github, https://github.com/trioZwShen/itrashcan.git
  2. ~/.bashrc中粘貼下面的設(shè)置環(huán)境變量, 并執(zhí)行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


二 功能實現(xiàn)

1 環(huán)境初始化

環(huán)境變量

# 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設(shè)置為腳本所在路徑
  • itrashcan_home設(shè)置為回收站的目標(biāo)位置, 回收站名稱可以自擬
  • config.sh中包含了itrashcan的命令別名

腳本

  • init.sh 執(zhí)行前需設(shè)置環(huán)境變量
    1. 檢查環(huán)境變量是否被設(shè)置
    2. 檢查回收站目標(biāo)位置是否有沖突
    3. 創(chuàng)建回收站
    4. 初始化腳本以及回收站的權(quán)限
#!/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. 該腳本首先會檢查環(huán)境是否已經(jīng)初始化, 沒有則init
    # init if the $itrashcan_home not exists
    if [ ! -d "$itrashcan_home" ]; then
        bash init.sh
    fi
    
  2. 檢查輸入是否正確, 如果-f選項, 那么使用real rm
  3. 利用lldu判斷目標(biāo)文件是否大于2G, 如果大于2G, 則會直接刪除
  4. 重命名回收站中的文件為filename_deletetime, 防止文件重名
  5. 獲取文件的絕對路徑, 用于恢復(fù)回收站文件
  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 恢復(fù)數(shù)據(jù)

restore.sh

  1. 檢查輸入
  2. 設(shè)置log路徑, 回收站路徑, 以及待查找的目標(biāo)模式findpattern
  3. 在log中查找目標(biāo)文件, 獲取同名文件數(shù)rowcount;
    • 如果有多個重名文件, 需要用戶自己確定恢復(fù)哪個
  4. 檢查回收站中該文件是否存在
  5. 檢查原路徑是否存在, 檢查原路徑中是否有重名文件
  6. 恢復(fù)數(shù)據(jù), 并刪除該記錄
#!/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
http://www.reibang.com/writer#/notebooks/27796113/notes/42433921/preview

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子骤铃,更是在濱河造成了極大的恐慌,老刑警劉巖航揉,帶你破解...
    沈念sama閱讀 221,635評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異金刁,居然都是意外死亡帅涂,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,543評論 3 399
  • 文/潘曉璐 我一進店門尤蛮,熙熙樓的掌柜王于貴愁眉苦臉地迎上來媳友,“玉大人,你說我怎么就攤上這事产捞〈济” “怎么了?”我有些...
    開封第一講書人閱讀 168,083評論 0 360
  • 文/不壞的土叔 我叫張陵坯临,是天一觀的道長焊唬。 經(jīng)常有香客問我,道長看靠,這世上最難降的妖魔是什么赶促? 我笑而不...
    開封第一講書人閱讀 59,640評論 1 296
  • 正文 為了忘掉前任,我火速辦了婚禮挟炬,結(jié)果婚禮上鸥滨,老公的妹妹穿的比我還像新娘嗦哆。我一直安慰自己,他們只是感情好爵赵,可當(dāng)我...
    茶點故事閱讀 68,640評論 6 397
  • 文/花漫 我一把揭開白布吝秕。 她就那樣靜靜地躺著泊脐,像睡著了一般空幻。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上容客,一...
    開封第一講書人閱讀 52,262評論 1 308
  • 那天秕铛,我揣著相機與錄音,去河邊找鬼缩挑。 笑死但两,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的供置。 我是一名探鬼主播谨湘,決...
    沈念sama閱讀 40,833評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼芥丧!你這毒婦竟也來了紧阔?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,736評論 0 276
  • 序言:老撾萬榮一對情侶失蹤续担,失蹤者是張志新(化名)和其女友劉穎擅耽,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體物遇,經(jīng)...
    沈念sama閱讀 46,280評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡乖仇,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,369評論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了询兴。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片乃沙。...
    茶點故事閱讀 40,503評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖诗舰,靈堂內(nèi)的尸體忽然破棺而出崔涂,到底是詐尸還是另有隱情,我是刑警寧澤始衅,帶...
    沈念sama閱讀 36,185評論 5 350
  • 正文 年R本政府宣布冷蚂,位于F島的核電站,受9級特大地震影響汛闸,放射性物質(zhì)發(fā)生泄漏蝙茶。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,870評論 3 333
  • 文/蒙蒙 一诸老、第九天 我趴在偏房一處隱蔽的房頂上張望隆夯。 院中可真熱鬧,春花似錦、人聲如沸蹄衷。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,340評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽愧口。三九已至睦番,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間耍属,已是汗流浹背托嚣。 一陣腳步聲響...
    開封第一講書人閱讀 33,460評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留厚骗,地道東北人示启。 一個月前我還...
    沈念sama閱讀 48,909評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像领舰,于是被迫代替她去往敵國和親夫嗓。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,512評論 2 359

推薦閱讀更多精彩內(nèi)容