0 Replies - 1024 Views - Last Post: 04 January 2008 - 09:02 PM

#1 Tom9729  Icon User is offline

  • Segmentation fault
  • member icon

Reputation: 181
  • View blog
  • Posts: 2,642
  • Joined: 30-December 07

Bash file limiter

Posted 04 January 2008 - 09:02 PM

Description: See "Installation" section in script header.This script counts the number of files in a directory. If the number of files exceeds a certain value, delete the oldest until the value is met. Ex. 10 files are in a directory, 5 new files are added. If the limit value is set to be 10, the 5 oldest files will be deleted.
#!/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


Is This A Good Question/Topic? 0
  • +

Page 1 of 1