Advertise on warmetal.nl!
Click for more information
about advertising here.

Did you find this website useful? Did I save you a lot of time?
Please consider donating to support this site:

 

Script: Bash: Find and remove old files

This is a short special page just dedicated to one command or script. The purpose here is just for me to learn scripting. I think most people will think these snippets are too simple too take notice from.
find /tmp/archive/. -type f -mtime +31 -exec rm {} \;
  • -type f makes sure only files are listed
  • -mtime +31 makes sure only files that are modified more than 31*24 hours are listed
  • -exec rm {} removes the files that find found
Note: If you have directories beneath the directories where you do your search take a look at the option -depth

Error

I got an error while running the line:
find /tmp/archive/* -prune -type f -mtime +31 -exec rm {} \;
 
/bin/sh: /usr/bin/find: Argument list too long

Turns out, find doesn't like '*', it needs the '.', as used in the example above.

Using Prune

If you don't want find to be recursive you can use the -maxdepth option. However, this option is not available in every version of find. I'm running AIX right now, with of course, a find that doesn't support that option. There is another option, but that just makes it completely non-recursive. From the man page:
To ignore a directory and the files under it, use -prune

But than, when I use the “find . -prune” prune will ignore the entire directory since '.' actually means the current directory. So to use this option you're forced to use '*':

find /var/data/* -prune -type f -name '*.txt2011*' -mtime +3 -print

Discussion

Enter your comment:
 
scriptbashfind.txt · Last modified: 2011/05/04 09:46 by sjoerd