Linux – Removing old cache files – command help

bashcommandcommand-line-interfacelinuxshell

I'm trying to write a command to help clear up old cache asset files. The files are always either .css,.javascript,.css.gzip or .javascript.gzip and i want to delete all files older than 2 days old.

I started with this command to test before passing to exec rm:

find /home/*/tmp/cache/* -mtime +2 -type f -name '*.css.gzip' -o -name '*.javascript.gzip' -o -name '*.javascript' -o -name '*.css'

This returns all the files i want deleting, so i've added rm making the command:

find /home/*/tmp/cache/* -mtime +2 -type f -name '*.css.gzip' -o -name '*.javascript.gzip' -o -name '*.javascript' -o -name '*.css' -exec rm {} \;

Nothing is actually getting deleted though, i tried making the rm command rm -i and there were no prompts, as if nothing is actually being passed to rm.

Any ideas?

FWIW this is on a CentOS 5 box

Best Answer

The issue is that adding -exec ... to the end of all those -o flags is tripping up precedence of AND vs OR, eg it's finding everything that is *.css.gzip OR *.javascript.gzip OR *.javascript OR (*.css AND delete it) so it only removes *.css but finds all the other files but does nothing with them. Incidentally it also means that your type and mtime flags are only applying to *.javascript.gzip.

Use

find /home/*/tmp/cache/* -mtime +2 -type f \( -name '*.css.gzip' -o -name '*.javascript.gzip' -o -name '*.javascript' -o -name '*.css' \) -exec rm {} \;

in order to force it to find all files with mtime +2 AND type f AND (all the different filename options) AND delete them.

To see this in action, replace -exec ... with -print in both your version and my version with ().

Related Topic