Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.

share|improve this question
3  
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
add comment

1 Answer

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
          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 {} +
share|improve this answer
    
-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
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.