How is it possible to delete files older than 14 days in a folder using a cron job? Everything I have tried so far hasn't worked.

  • 4
    In general, it is a good idea to include the things you have tried to i) show research effort and ii) so we don't suggest the same things. – terdon Oct 3 '13 at 1:46

You should be able to do that easily enough with find. Just run this command in your crontab (this will delete files and sub directories):

find /path/to/target -mtime +14 -delete

From man find

   -mtime n
          File's data was last modified n*24 hours ago.  

   Numeric arguments can be specified as

   +n     for greater than n,

   -n     for less than n,

   n      for exactly n.

          Delete files; true if removal succeeded.  If the removal failed,
          an  error message is issued.  If -delete fails, find's exit sta‐
          tus will be nonzero (when it eventually exits).  Use of  -delete
          automatically turns on the -depth option.

I am not sure if -delete is POSIX but if your implementation of find lacks -delete, you could also use

find /path/to/target -mtime +14 -exec rm {} +
  • -delete is not POSIX. Your two commands are not equivalent though. One will delete directories and the other won't. – jordanm Oct 3 '13 at 3:06
  • @jordanm yes but since the OP mentioned files, I thought it safer to use plain rm for the POSIX solution. I did warn that the first deletes directories as well. – terdon Oct 3 '13 at 3:09

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.