返回顶部

收藏

bash文件数量限制

更多

bash文件数量限制。该脚本对目录中文件数量进行计数,当数量超过一定值,则删除旧的文件。

比如10个文件在目录中,新增5个文件,如果限定值为10,那么最早的5个文件将被删除。

#!/usr/bin/bash
#
# Count files in a directory.
# If they exceed a set value, delete the oldest.
#
# Tom Arnold, 2007.
#
# Disclaimer: It should work fine, but use this at your own risk.
#             If you're working with valuable data, TEST THIS TH-
#             OROUGHLY BEFORE YOU USE IT.
#
# Installation: You should make this executable (chmod +x this_file.sh),
#               and place it somewhere like /etc/cron.daily (will be run
#               once a day.
#
#               Also, change the DIR and I variables below to whatever you
#               want.
#
# License: I don't care what you do with this, as long as you give me
#          credit. :)
##

## Set the working directory here.
DIR="../tmp/ahh"

## Our counter. Set this to the max number of files you want.
I=10

## Iterate through the working directory,
## Add filenames and dates to two seperate arrays.
X=0
for FILE in $DIR/*
do
    filenames[$X]=$FILE
    dates[$X]=$(stat -c %Y "$FILE")

    let X+=1
done

## If we don't have more than $I, just quit.
if [ $X -le $I ]; then
    break
fi

K=0
## Sort the filenames/dates from oldest to newest..
while [ $K -lt $X ];
do  
    ## Index of the max.
    let MI=0
    let MAX=0

    ## Current index.
    let l=0

    ## Run through the dates list once and get the oldest.
    while [ $l -lt $X ];
    do
    if [ ${dates[$l]} -gt $MAX ]; 
    then
        let MAX=${dates[$l]}
        let MI=$l
    fi

    let l+=1
    done

    ## Add the max to the new array, set the old one to something ridiculous, and count up K.
    filenames2[$K]=${filenames[$MI]}
    dates2[$K]=${dates[$MI]}
    dates[$MI]=-10
    let K+=1
done

## Count to $I, then start deleting.
W=0
while [ $W -lt $X ];
do
    if [ $W -ge $I ]; then
    #echo "Deleting "${filenames2[$W]}
    rm "${filenames2[$W]}"
    fi

    let W+=1
done
#该片段来自于http://outofmemory.cn

标签:shell,基础

收藏

0人收藏

支持

0

反对

0

相关聚客文章
  1. 博主 发表 2015-04-11 06:39:00 adb shell 基础: 看日志神器logcat
  2. 博主 发表 2015-04-11 06:10:00 adb 基础 ,重点在 adb shell ( adb basic )
  3. 博主 发表 2015-04-11 06:39:00 adb shell 基础: 看日志神器logcat
  4. 博主 发表 2015-04-11 06:10:00 adb 基础 ,重点在 adb shell ( adb basic )
  5. kingsamchen 发表 2015-06-27 09:16:20 使用cmder替换Windows自带的cmd
  6. 博主 发表 2015-07-14 02:57:17 AOS V0.2 发布,JavaEE 应用基础平台
  7. shang 发表 2015-07-31 09:27:05 linux通过shell脚本实现ftp自动更新
  8. 博主 发表 2015-08-19 00:00:00 fish 下使用 jenv
  9. DigDeeply 发表 2015-09-06 02:51:06 oh-my-zsh自动更改screen标题的问题解决
  10. 博主 发表 2015-07-15 03:24:44 常用Linux命令记录
  11. 果冻想 发表 2015-10-19 14:50:23 玩玩awk
  12. admin 发表 2015-11-03 13:55:43 写个添加svn帐户的脚本

发表评论