linux-shell 按时间排序保留最新的N个文件夹

时间:2024-04-15 12:41:37
#!/bin/sh

if [ -z $1 ] || [ -z $2 ];then
    echo -e "usage: ./folder_save.sh [save num of int] [deal with path]"
    exit
fi

echo -e "0=$0,1=$1, 2=$2"

basedir=$(cd `dirname $0`;pwd)
dealwithdir=$2 #/home/afc/savefiles
DATE=$(date "+%F %H:%M")
#path=${basedir}/test
save_num=$1
line=$(ls -l ${dealwithdir}|sed 1d|wc -l)
if [ ! $basedir/del_name.log ];then   
   touch $basedir/del_name.log
fi

   echo "------------------------$DATE------------------------"  >>$basedir/del_name.log

if [ $save_num -lt $line ];then
   echo "----------------delete dealwithdir is $dealwithdir-------------------" >>$basedir/del_name.log
   ls -t $dealwithdir|awk "{if(NR>$save_num){print \$1}}" >>$basedir/del_name.log
   cd $dealwithdir
   ls -t|awk "{if(NR>$save_num){print \$1}}"|xargs rm -rf 
else
   echo "$dealwithdir wenjian number is ok" >>$basedir/del_name.log
fi