Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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
add comment

2 Answers

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

Assumptions:

  • 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

#!/bin/bash

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

# directory to search
DIR=/Users/danielbeck/test

# max folder size in KB
MAXSIZE=1000

# 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"

 done

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
add comment

Another shell script:

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

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/script.sh

share|improve this answer
add comment

Your Answer

 
discard

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.