linux 实现回收站功能

来源:互联网 发布:辅仁大学 知乎 编辑:程序博客网 时间:2024/05/31 11:03


话不多说,直接代码: 


#!/bin/sh

# 创建回收站目录
MYRM="/var/tmp/rm"


if [ ! -d ${MYRM} ]; then
    mkdir ${MYRM}
fi


# 移动文件到回收站
function mvFile()
{
    filePath=$1;                # 删除到文件
    rmPath=$2;                  # 回收站目录
    fileName=${filePath##*/};   # 删除到文件名
    fileNoSuf=${fileName%.*};   # 删除到文件名(不包含后缀)
    noSufLen=${#fileNoSuf};     # 不包含后缀到文件名长度,用来计算后缀

    fileSuffix=.${fileName:${noSufLen}}; #文件名到后缀


    tmpFile=${rmPath}/${fileName};
    # 如果回收站中不存在重名文件,直接拷贝,如果存在则重新命名文件名在拷贝
    if [ ! -d $tmpFile ] && [ ! -f $tmpFile ]; then
        mv $filePath $tmpFile 1>&2 2>/dev/null;
    else
        for i in {1..10000}; do
            tmpFile=${rmPath}/${fileNoSuf}\(${i}\)${fileSuffix};
            if [ ! -f $tmpFile ]; then
                mv $filePath $tmpFile 1>&2 2>/dev/null;
                break;
            fi
        done
    fi
}


# 移动目录
function mvDir()
{
    filePath=$1;
    rmPath=$2;
    fileName=${filePath##*/};


    tmpFile=${rmPath}/${fileName};
    # 如果回收站中不存在重名目录,直接拷贝,如果存在则重新命名目录名在拷贝
    if [ ! -d $tmpFile ] && [ ! -f $tmpFile ]; then
        mv $filePath $tmpFile 1>&2 2>/dev/null;
    else
        for i in {1..10000}; do
            tmpFile=${rmPath}/${fileName}\(${i}\);
            if [ ! -d $tmpFile ]; then
                mv $filePath $tmpFile 1>&2 2>/dev/null;
                break;
            fi
        done
    fi
}


#检查输入文件,目录是否存在
for file in $*; do
    # 如果不存在该目录,则移动到该目录,如果存在,则修改文件名在移动
    if [ -d ${file} ]; then
        mvDir $file $MYRM
    fi

    if [ -f $file ]; then
        mvFile $file $MYRM
    fi


# mv -fb $file $MYRM
done