Linux – Bash script to delete files older than x days with subdirectories

findlinux

I'm trying to delete a ton of files older than x days.

Now I have a script to do that

find /path/to/files* -mtime +10 -exec rm {} \; 

But this will also delete the subdirectories. There are a ton of folders but I would like to keep them, and delete the files older than 10 days within the said folders.

Is there a way to do this?

Best Answer

type option for filtering results

find accepts the type option for selecting, for example, only files.

find /path/to/files -type f -mtime +10 -delete

Leave out -delete to show what it'd delete, and once you've verified that, go ahead and run the full command.

That would only run on files, not directories. Use -type d for the inverse, only listing directories that match your arguments.


Additional options

You might want to read man find, as there are some more options you could need in the future. For example, -maxdepth would allow you to only restrict the found items to a specific depth, e.g. -maxdepth 0 would not recurse into subdirectories.

Some remarks

  • I wonder how the command would have removed a folder, since you can't remove a folder with rm only. You'd need rm -r for that.

  • Also, /path/to/files* is confusing. Did you mean /path/to/files/ or are you expecting the wildcard to expand to several file and folder names?

  • Put the {} in single quotes, i.e. '{}' to avoid the substituted file/directory name to be interpreted by the shell, just like we protect the semicolon with a backslash.

Related Question