find files older than 30 days old

Hello,

I have a script which finds files in a directory that are older than 30 days and remove them.
The problem is that these files are too many and when i run this command:

 
find * -mtime +30 | xargs rm

I run this command inside the directory and it returns the error:
/usr/bin/find: 0403-027 The parameter list is too long.

Is there another command instead of find which does not produce this kind of problem?

Thank you for your attention

Try

 
find /home/amit/log/ -mtime +30 -exec rm {} \;

You are wise to use xargs as it's much more efficient. The "splat" (*) on your command line is expanding to all files in the directory. What you want is to search in your current directory:

find . -mtime +30 | xargs rm 
1 Like

If the version of find being used supports it, I usually use the -delete option as it is usually even faster. Implementations differ but usually the -exec option of find does a fork() and then an execvp(), and then waits on the child process. It starts a child process for each file which makes it slow. xargs does the same thing but calls vfork() and concatenates the argument list and usually only creates one child process. The -delete option simply does an rmdir() or unlink() as it is walking the filesystem tree and it is usually as fast or faster than xargs in my experience. Also by using -delete you don't run into the number of arguments hard limit that xargs imposes (or rather execvp(3)). By default, -delete deletes both files and directories, so if the intention is only to delete files, the -type parameter must also be specified. Of course, if it is a script that is being run often, it doesn't hurt to profile and determine which is best.

I usually do:

find . -type f -mtime +30 -delete
1 Like

thank you guys for your tips
i tried

find . -mtime +30 | xargs rm

and it worked perfectly!

find . -type f -mtime +30 | xargs rm

Is safer.

yes i agree but since i call the argument rm and not rm -r then it cannot delete directories anyway

1 Like

try:

find . -name "***xxxx***" -type d -atime -30 -print | xargs -exec rm -fr

replace the text in quotes by directory name. I am guessing you get a lot of directories with similar names.

Caution: use above command without the rm part to just check if you are getting the dir names to be deleted.

This command is extremely dangerous and unlikely to produce any sensible result. Remember that "find" itself changes the "-atime" timestamp on a directory as does most backup software.

1 Like