Linux – Command that deletes all old files, folders and sub-folders

filesfindlinuxrm

I need a command that deletes all files, folders and sub-folders that were not updated longer than 31 days.
I tried this one

find . -mindepth 1 -mtime +31 -exec rm -rf "{}" \;

But if I have hierarchy like this

.
├── old_sub_folder1
└── old_sub_folder2
    ├── old_file
    └── old_sub_folder3
        └── new_file

where old_* are old folders\files and new_file is a new file.

This command will delete all contents. Because old_sub_folder2 date was not updated after new_file was created.

I need a command that would not delete old_sub_folder2/old_sub_folder3/new_file

Best Answer

The problem is that you added the -r option to your rm command. This will delete the folders even if they are not empty.

You need to do this in two steps:

  1. Delete only the old files:

    find . -type f -mtime +31 -delete

  2. To delete any old folders, if they are empty, we can take a peek here, and tweak it a bit:

    find . -type d -empty -mtime +31 -delete

Related Question