如何基于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
http://www.lxweimin.com/writer#/notebooks/27796113/notes/42433921/preview

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,345評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,494評論 3 416
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,283評論 0 374
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,953評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,714評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,186評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,255評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,410評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,940評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,776評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,976評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,518評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,210評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,642評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,878評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,654評論 3 391
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,958評論 2 373

推薦閱讀更多精彩內容