2

I have this unique requirement of finding 2 years older files and delete them. But not only files as well as corresponding empty directories. I have written most of the logic but only thing that is still pending is , when I delete particular file from a directory , How can I delete the corresponding directory when it is empty. As when I delete the particular file , the ctime/mtime would also accordingly get updated. How do I target those corresponding older directories and delete them? Any pointers will be helpful. Thanks in advance.

  • Admin
Sachin H
  • 37
  • 6

1 Answers1

3

I would do something like this:

find /path/to/files* -mtime +730 -delete

-mtime +730 finds files which are older than 730 days.

Please be careful with this kind of command though, be sure to write find /path/to/files* -mtime +730 beforehand and check that these are the files you want to delete!

Edit: Now you have deleted the files from the directories, -mtime +730 won't work. To delete all empty directories that you have recently altered:

find . -type d -mmin -60 -empty -delete
Luke Garrigan
  • 4,571
  • 1
  • 21
  • 29
  • Thanks for the reply. Yes that makes sense and like mentioned before , I have got so far. The part which is still pending is , how do I target(delete) the directories which will be empty after I delete the older files within. – Sachin H Apr 04 '17 at 11:34
  • Sure, so you want to delete the now empty directories, check my edit @SachinH – Luke Garrigan Apr 04 '17 at 11:39
  • Sorry but you missed the point again. Once you delete the older files the corresponding empty directory will no longer be *old* i.e will mtime and ctime be modified. – Sachin H Apr 04 '17 at 12:19
  • @SachinH So then just delete all the old directories initially? `find . -type d -mtime +730 -exec rm -rv {} \;` – Luke Garrigan Apr 04 '17 at 12:46
  • If you mean you want to delete all the files older than 2 years and then check if that directory is empty you should probably write a script to do so, else just do one then the other @SachinH – Luke Garrigan Apr 04 '17 at 12:49
  • That would be very risky as the users constantly update those directories. – Sachin H Apr 04 '17 at 13:04
  • If you ever did find a risk-free method of doing this I'd love to see it, thank you @SachinH – Luke Garrigan Apr 07 '17 at 13:21