日期:2014-05-16  浏览次数:20407 次

一个安全删除文件的shell命令

以下脚本中的函数可以安全用来删除

delete xxxx

该命令会将xxx文件(或目录(不要再目录后加/))移动的~/backup下面,并同时打上时间标签,通过运行

delete_old

会将~/backup目录下的超过3000M的最旧的文件或目录删除掉,希望数据保护还是有一定的用处


# Description:  This function used to move some useless files in current folder to ~/backup/
#      Author:  fulinux
#     Version:  1.0.0 (Release by fulinux on 8th April. 2013)


function delete ()
{
   if [ -z $1 ]; then
      echo "delete it to backuo directory"
      echo "Usage: $FUNCNAME [express]"
      echo "Example: $FUNCNAME fulinux/"
      return;
   fi


   express=$1
   timestamp=$(date +%Y%m%d%H%M%S)


   rechristen=$1.$timestamp


   mv "$express" ~/backup/"$rechristen"
}


# Description:  This function used to search dir to fetch the oldest file
#      Author:  fulinux
#     Version:  1.0.0 (Release by fulinux on 8th April. 2013)


searchdir()
{
    oldestfile=`ls -rt | head -n 1 |awk '{print $1}'`
}


# Description:  This function used to remove oldest useless files in ~/backup folder if its size is more than 4000M
#      Author:  fulinux
#     Version:  1.0.0 (Release by fulinux on 8th April. 2013)


#This is the directory where backup files are kept
backup=~/backup
#maximum useless files
alarmrate=3000


function delete_old()
{
    cd $backup
    while true;
    do
        backup_size=`du -ms $backup | awk '{print $1}'`
        if [ $backup_size -gt $alarmrate ];
        then
            searchdir
            delete $oldestfile
        else
            break;
        fi
    done
}