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.

I'd like to run a nightly cron job that deletes all the files in a folder that haven't been accessed in a week or more. What is the most efficient way to do this in bash?

share|improve this question

migrated from stackoverflow.com Jul 13 '11 at 1:01

This question came from our site for professional and enthusiast programmers.

2  
find can filter based on atime. The "correctness" of atime depends upon configuration (see noatime), at the very least. –  pst Jul 12 '11 at 23:40
add comment

2 Answers 2

up vote 15 down vote accepted

You want the find tool.

find folder -depth -type f -atime +7 -delete

(This will delete all files (only regular ones, no pipes, special devices, directories, symbolic links) in the given folder and all subdirectories (recursively) where the last access time is longer than 7 days ago.)

share|improve this answer
4  
You might want to add -type f in there to ensure it only deletes files, not entire directories. –  Shadur Jul 13 '11 at 4:42
add comment

You may want to check out tmpwatch which can be put into a cron job. No need to roll-your-own with find. On RHEL it's in the tmpwatch RPM.

share|improve this answer
    
This is definitely the more elegant solution, but I prefer the portability of find. –  bloudermilk Jul 15 '11 at 3:21
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.