2

I have a backup folder than uses a calendar like folder structure to organise files. I want to delete these every 5 days but I end up deleting the full backup because the main folder is older than 5 days.

Folder structure:

Backup
    -> 2017
          -> October
                 -> 28
                 -> 29
                 -> 30
                 -> 31
          -> November
                 -> 1
                 -> 2
                 -> 3

I've tried running this command:

find /mnt/backup/* -type d -mtime +5 -execdir rm -rf {} \;

But it will remove the directory 2017 because it is older than 5 days, which in turn means it will remove all the subfolders. I only want to delete directories inside here that are 5 days old. For example if today was November 3rd I only want to have the directories 28 and 29 to delete. Then when it becomes 5th November I want the full October directory to be deleted as everything in there will now be older than 5 days. Any suggestions?

Thanks

  • 1
    Use -mindepth 1 so that find always only checks subdirectories of 2017? Also, find has a -delete action you can use instead of -execdir rm -rf ... – muru Oct 10 '17 at 8:40
  • Maybe I've missed something, but is there a reason why you can't specify the 2017 directory in the original find request? I.e. find /mnt/backup/2017/* instead of find /mnt/backup/* – The Pizza Overlord Oct 10 '17 at 8:43
  • What happens then when 2017 turns to 2018? Will I have to manually come along then and delete 2017? - That's the reason @ThePizzaOverlord – Stuart Oct 10 '17 at 8:50
  • 1
    @Stuart - thought that may have been the case. In the example I gave, yeah, but like most people seem to be agreeing on, you can just use -mindepth 1 to skip over ANY subdirectory on the same 'level' (aka depth) – The Pizza Overlord Oct 10 '17 at 8:58
3

Use -mindepth 1 if you don't want 2017 to be touched:

$ mkdir -p foo/2017/{October/{28..31},November/{1..3}}
$ touch -d 'now - 6 days' foo/2017/October/{28,29} foo/2017
$ find foo/* -mindepth 1 -mtime +5
foo/2017/October/28
foo/2017/October/29
$ find foo/* -mtime +5
foo/2017
foo/2017/October/28
foo/2017/October/29

If you start from foo instead of foo/2017, then use -mindepth 2:

$ find foo/ -mindepth 2 -mtime +5
foo/2017/October/28
foo/2017/October/29

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.