0

What if I want to delete files/folders that are not accessed for a few days in Unix? Say there are some files that were last accessed 5 days ago in a particular location. I want to delete those. What is the shell command for that?

2 Answers2

2

The find command is what you need, with its -atime and, possibly, -daystart options.

Start with this to make sure its finding what you need (and nothing you don't!):

find directory -atime +5 -daystart -ls 

Then, once you're happy, get it to do the real work:

find directory -atime +5 -daystart -exec rm {} \; 
Phill W.
  • 1,336
  • 7
  • 7
  • 3
    If the volume is mounted with the noatime option, this will not work. Then again neither will any other methods that depend on atime values being incremented. – Rik Schneider Mar 19 '20 at 13:39
0

While find is portable and will work from a variety of operating systems, -daystart -ls is not POSIX. If you know you are using GNU findutils, might as well use -delete instead and skip shelling out to rm.

Or, consider installing and using tmpwatch. You can provide any or all of access time, modification time, or inode change time, and if multiple are provided the older is evaluated. Further, there are safety checks, so it is not going to escape the given tree.

File list dry run.

tmpwatch --verbose --test --atime 5d /tmp

Actually removing.

tmpwatch --verbose --atime 5d /tmp

John Mahowald
  • 30,009
  • 1
  • 17
  • 32