Introduction

In this tutorial, we are going to talk about locate command that can help you find files and directories.

The locate command - a fast find

The locate command is similar to the find command that you can tell it what to look for, and it will return a list of results that match your search pattern. Note: you don't need to specify the full pattern in locate command.

locate pattern

locate is faster than the find command. The find command looks through the path you gave it and evaluates each file and directory and determines if that matches your search pattern or not and then returns those results. The locate command, however, works off of an index. Typically, the index is rebuilt every day. Instead of evaluating each and every file to see if it matches the pattern, locate just does a lookup in the index. What you need to know about this is that the results are not in real time. There is a lag between the time that the index gets created and the time that you run the locate command.

So if you are looking for a file that was created just couple minutes ago, chances are it is not going to be in the index. You only hope for finding that file is with the find command that evaluates files and directories in real time.

In addition, on some systems, locate is not enabled by default.

Examples

Example 1: use locate

Use locate to find files and directories that have 'hello' in the name.

$ locate hello
Example 2: search file that just been created

Use locate to find a file that just been created.

$ touch new_file
$ locate new_file

You won't be able to find the 'new_file' because the index is not up-to-date. You can use find command to search the file in real time.

$ find . -name new_file
/home/robin/new_file

References & Resources