1

I have a folder /data and inside there I have many folders.. I want to remove the contents of these directories after 30 days of creation, but not the directory itself.

So my path would be /data/dirname/files or /data/dirname/anotherdir/files.

The first dirname needs to be saved since it is shared via FTP.

When the script or command is done I guess crontabbing it would be a good idea, right?

How would I do this?

4

You can recursively list all regular files under \data that were last modified 30 days ago with

find /data -type f -mtime +30 -ls

But you have to note that mtime isn't necessarily the time of creation. I don't think that it's possible to check for time of creation. You just have ctime, atime and mtime to check for.

If you want to delete those files you can invoke a similar command

find /data -type f -mtime +30 -delete

Of course you can add this command to your crontab file.

2

Here's my suggestion:

find /data -type f -a -ctime +30 -print0 | xargs --no-run-if-empty -0 rm -f

find /data -type l -a -ctime +30 -print0 | xargs --no-run-if-empty -0 rm -f

find /data -type d -mindepth 1 -print0 | xargs --no-run-if-empty -0 rmdir --ignore-fail-on-non-empty

It's a bit more elaborate, but it cleans up files, symlinks and empty directories. The --no-run-if-empty, -f and --ignore-fail-on-non-empty options prevent mails from your cronjob in case something can't be cleaned up.

I'm using ctime; using mtime has the disadvantage that if you unpack a zip or tar file, dates will mostly be in the past, causing the files to disappear after just one day. Empty directories are removed immediately, though.

4
  • WHy don't you just run this as a single find command without specifying -type? That way you can do files links and directories in one fell swoop and pass them to rm -rf.
    – terdon
    Aug 1 '13 at 14:44
  • Because that will delete directories with content, regardless of the age of the files in it...
    – JvO
    Aug 1 '13 at 16:02
  • True, but the age of the directory should be the same as its newest file.
    – terdon
    Aug 1 '13 at 16:03
  • 1
    That's a dangerous assumption. Plus, any file removal/addition in a directory will also change it ctime stamp, causing the empty directory to linger for another 30 days. So, for example, a 4-level deep directory will take 120 days to get cleaned up completely. That script comes from experience :)
    – JvO
    Aug 1 '13 at 16:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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