Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'd like to create directory with a maximum size of, let's say 500MB. The directory may contain any number and depth of subdirectories.

When the maximum size limit of the directory is surpassed, I would like to purge the directory of the last accessed file(s) until it is back under the size limit. Ideally, empty directories would be cleaned out during this purge operation.

This doesn't need to happen in real time -- i.e., it's okay if the directory goes over the maximum, just as long as it's regularly purged.

I've explored a few options. I could mount the folder as a separate file system and run quota on that, but that doesn't help with intelligently purging of old files. I looked at (mis)using logrotate for this purpose, but it doesn't handle limitless recursion very well, nor does it have a facility for purging by starting from the oldest file.

Without a better suggestion, my plan is to brush up on my bash skills and write a script that checks the directory size via du -s, and if it finds the directory to be larger than the maximum, then it recursively finds all the files in the directory, sorts them by access date oldest first, then deletes them one by one, checking the directory size and exiting when the directory is back under the target. This script could be run as a cron job.

I'm just wondering if I'm overlooking an existing tool or strategy that handles this more easily.

(If you're curious why I'm asking, I'm using s3fs to mount Amazon S3 buckets on a local file system, and I'm investigating using the use_cache option to maintain a local cache. Since S3 buckets can get quite large, I need a way to intelligently manage this cache.)

Edit: tmpreaper is another tool I just found out about that's pretty close to doing the job. It only seems able to clean out folders based on access time (not a size limit), but in all other respects it appears to be a good choice.

share|improve this question
Is there a reason you want to use a shell script instead of Perl or a similar language. The built in data types will make it easier. – David Mar 4 '13 at 22:52
@David Good point, and I will probably do that (with Python) if I end up needing to implement it on my own. – Jim D Mar 5 '13 at 2:35

All what you need is to use the script posted here ( You only need to define $TrashPath.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.