Find v/s Locate … Optimize your search ..

16 / Sep / 2011 by Manoj Mohan 0 comments

A few days back, I was on a server wherein I had to find the location of a file in the file system. Naturally like most newbies, I instantly hit the ‘find’ command.  Something like

[shell]sudo find / -name someFileName.ext[/shell]

Naturally the command took a lot of time to find the file (Local to server relay not being helpful either).
At one point it grew so frustrating that I had to stop it and search for an alternative . Thats when I met Locate.. The lesser known brother of Find, WhereIs and Grep.

As soon as i hit the command

[shell]locate someFileName.ext[/shell]


The result popped up.. in less than a second !!!
This was a real time saving alternative. Comparing 1 sec to over 20 sec and that too over a remote server, man I could have killed for this sort of performance. Thanks to ‘locate’ for having saved me some prison time 😀 .

Now here’s the real thing …
Locate searches for files from a database that is created automatically. This database contains the list of files in a file system and their associated paths. So essentially locate simply searches through a file and returns a match.
Find on the other hand searches through files in the file system in real time. It’ll definitely be slower because it will search each and every path recursively from it’s start point.

Locate therefore is much faster as compared to find when searching for unique items.

But there are a few disadvantages to this method as well.

Locate might miss out on files created within a 24 hour period. This is because the database through which locate searches is updated automatically through a cron job that usually runs in 24 hour intervals. Find is the winner here … however to manually run the job for updating the database in Ubuntu, you can simply run a command

[shell]sudo updatedb[/shell]

and get the job done.

Find also contains a number of filters like  specifying type -d (Directory) which aren’t present in locate.  This means that locate command for a directory would return files as well as directories. So in essence locate returns a large number of results whereas find can narrow them down.

Essentially it’s the situation that should describe which command to use. But I would still suggest you give locate a try. You would be pleasantly surprised.

Manoj Mohan

Leave a Reply

Your email address will not be published. Required fields are marked *