find vs locate: Save your time
Both the commands: find and locate serve the same purposes- find file names. Then which one is a better option to search for files. But before moving on to telling the difference, let me tell you how locate command works
The working of locate command.
locate makes use of a database for its proper execution. locate.updatedb or updatedb is a command which is executed in the background periodically (mostly on weekly basis). updatedb creates a database of filenames present in your machine. So the next time if you are searching for a file name, you will find the file name within a fraction of time. Because locate will not search for the file names on the fly but rather it searches the database. Now the question that may come to your mind, what if the file is deleted. Yes, you got the point. locate will not be able to tell you that.
Search a file or a directory using locate
Let’s suppose we are searching for a file or a directory named user
$ locate user /home/user/directory /home/abc/user.txt
For case insensitive search, use the -i option
$ locate -i user
As you can see, you need not specify the path where you want to search for a file, becuase locate will find all the paths. So to filter out the results, you can use grep.
Search using find
Unlike locate, find needs the path and also whether you are looking for the file name or the pattern anywhere in a path name
Take for example, you are looking for a file with a name user.
$ls /home/abc/ user.text $ find /home/abc -name user
You may be wondering why you didn’t get any output. This is because, you didn’t specify the complete file name. There are some things which you should be careful while working with find.
- Always use the case insensitive search. Use the -i option
- If you are not sure about the file name, make sure that you use regular expressions
Now we will search again
$ find /home/abc/ -iname "*user*" /home/abc/user.txt
find vs locate: Difference
Now you may be clear about the difference
- find searches for file names on the fly whereas locate uses the periodic database to search for filenames
- find is slow whereas locate is pretty fast
- find gives you accurate results whereas locate may not (A new file created or an old file deleted after the weekly updation of locate database may not be reflected in locate results)
- find requires the directory where you want to perform the search whereas locate does not need any such option
So now to the uses, if you are searching for old files, system configuration files, manual pages, installation directories of packages, use locate. where as find can be used for all purposes.
Comments: