Nov 9th 2006


Using find

Find is part of the staple diet of any seasoned Unix admin, but to many times I see people struggling with some file maintenance operation across recursive directories when a simple one liner using find would have the job done in seconds.

For example, from the days when my (rather large) music collection sat on a Windows box there are loads of desktop.ini and thumbs.db folders thrown all around the very complicated folder structure.  A quick way to clear these using find would be to cd to the top level of my music collection and do  something like

 find ./ -name \*.ini -exec rm {} \;

In this example find will return anything ending in .ini from the current directory downwards and then execute rm with the matches passed to it.  

However it is easy to see how that could be quite dangerous, if for example I had forgotten to change directories first it may have run against my home directory or worse perhaps I was silly enough to run it as root and am sitting in /.

Ok bad example because there aren't many important .ini files in Linux, but you see my point.  A far safer way would be to substitute -ok for -exec in the above command, this will prompt me for the specified action for each match. However if find returns many matches then pressing "y" for each one is a little cumbersome.

 One good safety measure is to include the absoulte path in the find command, so in this example.

 find /home/share/tunes -name \*.ini -exec rm {} \;

Would only work against my music folder, regardless of which directory I am in when I run it. Another good tip is to dry run find to simply output the matches first and then visually check that the output is what you expected.

find /home/share/tunes -name *.ini -print

Would return the names of the files that would be deleted if I ran the full command.  Of course rm isn't the only command we can run here, we can use find to recursively run pretty much any command against a directory structure. find has very powerful searching filters that can accept regular expressions and search things like file creation/modify dates. Check out the man pages for more information of this useful and often essential little utility.


leave a comment

Sorry I hate these captcha things as much as anyone, but I hate people advertising viagra on my site even more so I need to you to complete the test below: