Super User is a question and answer site for computer enthusiasts and power users. 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 run OS X and have a security camera writing images to a folder.

Is there a way to limit this folder's size and then delete the oldest file?

share|improve this question
Yes, you may need to make a script to do it though. Have you ever programed or written scripts? – nerdwaller Aug 2 '13 at 2:40
Welcome to super user, for future reference, you should read the help. It is good to list the things that you have tried in your questions. – spuder Aug 2 '13 at 6:15
Is the camera naming the files in any pattern? The answers given will delete things based on the time they were last modified (because *nixes like OSX don't store the creation time); the only way to be really sure of getting the oldest ones created is if the security camera is embedding the date/time in either the filename or some metadata. – evilsoup Aug 2 '13 at 20:16

The following shell script deletes the oldest file in the given folder repeatedly until the folder size is below a specified maximum total.


  • You have GNU find installed, e.g. findutils from Homebrew
  • Doesn't work when files are added faster than the folder size can be determined


# defensive
set -o nounset
set -o errexit
set -o pipefail

# directory to search

# max folder size in KB

# as long as folder size is greater than limit
while [[ $( du -sk "$DIR" | cut -f1 ) -gt $MAXSIZE ]] ; do

    # find the oldest file (modification time counts)
    FILE="$( gfind "$DIR" -type f -printf '%T+ %p\n' | sort -n | head -n1 | cut -d' ' -f2- )"

    # delete it
    /bin/rm -v "$FILE"


You can modify this script a bit to have it run persistently in the background (using e.g. screen), or have it launch every minute (or every few minutes) using e.g. cron.

share|improve this answer

Another shell script:

cd ~/directory
for f in $(ls -t); do
  sum+=$(stat -f%z "$f")
  ((sum > 10*8)) && rm "$f"

10*8 is 100 MB. If the file names contain spaces, add IFS=$'\n' before for. If the file names can be interpreted as glob patterns, use set -f or replace the for loop with something like while IFS= read -r l; do :; done < <(ls -t). Use -c%s instead of -f%z with GNU stat.

You can run the script every three hours by running EDITOR=nano crontab -e and adding a line like this:

0 */3 * * * bash ~/path/to/

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .