Script to Limit Number of Files in a Directory

I have some jobs that run and will fill up disk drives if not pruned.

I put together the simple script below that I can call with a directory and the number of files I want to keep. The oldest files will be deleted. I add it to cron jobs with a command in this pattern:

~/ ~/public_html/FrontDoor/Camera\ 01 200
Note: there are 2 params, the \ escapes the space before the 01
Copy into


for line in `ls -t "$1"`
  if [[ $Cnt -gt $limit ]]
    rm "$dir/$line"
    echo "rm $dir/$line"
  Cnt=`expr $Cnt + 1`

While I know this is not the most professional way to do this, I wanted something very simple I could play with and should have few dependencies so I could use it on shared servers that I do not have control over.

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *