shell 定期删除文件夹中最旧的文件

#检查文件夹,文件数量大于参数的时候,从最久的开始删起
clear_old_files(){
    if [ ! $# -eq 2 ];then
        log_ "invalid parameter for clear_old_files():"$*
        return
    fi

    dir=$1
    count_limit=$2
    if [ ! -d $dir ];then
        log_ "$dir is not a directory"
        return
    fi

    file_count=`ls -l $dir| grep ^- | wc -l`    
    if [ $file_count -lt $count_limit ];then
        # log_ "current file count="$file_count", which is lower than limit:"$count_limit
        return
    fi
    log_ "current file count=$file_count, bigger than limit=$count_limit"

    #删除最久的一些文件
    file_count=`ls -l $dir| grep ^- | wc -l`    
    old_file=$(ls -rt $dir|head -1)

    while (( $file_count>$count_limit ))
    do
        log_ "delete file $dir/$old_file"
        rm -f $dir/$old_file
        let "file_count--"
        old_file=$(ls -rt $dir|head -1)
    done
}

clear_old_files /tmp/dir_to_delete 300

保留300个最新的,其他删除