The Locate command (Linux)


To totally unlock this section you need to Log-in


If there is something that is quite vital, on Linux systems in CLI mode (no GUIs, no KDE or Gnome), is to have a simple way to search for specific files/folders on the filesystem. To do this we can install and use the locate utility, on Linux systems.

locate command in Linux is used to find the files by name. It is not the only utility that we can use to do this kind of activity, because there is also the find approach.

But, the locate utility works better and faster than find command counterpart because instead of searching the file system when a file search is initiated, it would look through a database. This database contains bits and parts of files and their corresponding paths on your system.

By default, locate command does not check whether the files found in the database still exist and it never reports files created after the most recent update of the relevant database.

Linux does not come with the locate command pre-installed. To get the package, run the following commands one after another:

##### On Debian/Ubuntu ########
sudo apt-get update
sudo apt-get install locate
sudo apt-get install mlocate

##### On RHEL/Centos/Fedora ########
sudo yum install -y mlocate

Considering the most basic systax that we have available, we can now use the command to search for files using the following approach:

locate [my-file]

Please note that if you run locate command immediately after installing mlocate package then you will get the error "locate: can not stat () '/var/lib/mlocate/mlocate.db': No such file or directory".

The vanilla locate command can sometimes return files that have been deleted, if the database wasn’t updated. The best solution is to manually update the database by running the following:

sudo updatedb

For the curious, the database is located at /var/lib/mlocate/mlocate.db on some systems (if mlocate package has been installed on system), such as Red Hat and Debian. Its exact location on any particular system can be found by the root user (because ordinary users will not have access permission on most systems) with the locate command as follows:

locate locate.db

The database is a binary file (i.e., a non-text file). However, for the really curious user who has root permission, the human-readable portion of its contents can be viewed by first using the strings command to extract all the plain text and by then piping the output to less for displaying one screenful at a time as follows:

strings /var/lib/mlocate/mlocate.db | less

Talking about indexes of the locate utility, if we want to create an index of the present directory (and its subdirectories), we can use the updatedb command like this:

sudo updatedb -l0 -U my_directory -o index_file

Once we have created this index file, we can ask locate command to explicitly use this index (the index_file we have just created):

locate -d index_file file_name

In general, the result of any locate request will show all the places/locations where the file we specified has been found; below an example:

[email protected]:~$ locate desktop.iso
/home/dummy/desktop.iso
/home/to_delete/really/old_desktop.iso

NOTE (mlocate):Please make sure to check the access of the user before searching a file as current logged in user might not have permission to search in all the files and directories. You will not see "Permission Denied" error while running locate command from non-privileged user id like you get in find command search. It will simply not look into those directories where it is not allowed.

The best part is that we don't need to be in the certain directory to find the file. Remember, locate command doesn’t search the filesystem but the index. This is why we don’t need to specify a path or directory while looking for files.

The following are some sample usage scenarios for the locate utility.

Limit Search Queries to a Specific Number

$ locate "*.html" -l 20

It will show 20 results for the searching of file ending with .html.

Display The Number of Matching Entries

$ locate -c [.txt]*

It will count files ending with .txt.

Separate Output Entries Without New Line

$ locate -i -0 *sample.txt*

Default separator for locate command is the newline (\\n) character. But if someone want to use a different separator like the ASCII NUL, the he/she can do so using the -0 command line option.

Disables Errors While Searching

-q option will prevent any errors from showing up when the search is being processed. To do this, simply enter:

locate -q my-file

Search Exact File Name

The basic syntax only allows you to search for files that contain the search term. If we want to get the file with the exact name, you can use the -r option and add dollar symbol ($) at the end of your search term, for example:

locate -r my-file$

If you need to run a more complex search, use the -r (--regexp) option, which allows you to search using a basic regexp instead of patterns. This option can be specified multiple times. For example, to search for all .mp4 and .avi files on your system and ignore case, you would run:

locate --regex -i "(\.mp4|\.avi)"

locate or mlocate?

On some Linux distributions (especially Debian-based ones) there are two packages that provide the locate utility: locate and mlocate.

The locate package is the implementation of locate from GNU findutils.

The mlocate package is another implementation of the same concept called mlocate.

They implement the same basic functionality: quick lookup of file names based on an index that's (typically) rebuilt every night. They differ in some of their functionality beyond basic usage.

In particular, GNU locate builds an index of world-readable files only (unless you run it from your account), whereas mlocate builds an index of all files but only lets the calling user see files that it could access. This makes mlocate more useful in most circumstances, but unusable in some unusual installations where it isn't run by the system administrator (because mlocate has to be setuid root), and a security risk.

Under Debian and derivatives, if you install both, locate will run the mlocate implementation, and you need to run locate.findutils to run the GNU implementation (so, the legacy locate). This is managed through alternatives.

If you have both installed, they'll both spend time rebuilding their respective index, but other than that they won't conflict with each other.

mlocate is a newer implemenation of locate.

The following snapshot shows the different syntax provided by mlocate and locate on the same Debian-based distro (mlocate and locate installed on the same system):

Syntax (mlocate and locate.findutils)

The following is the syntax for locate.findutils (locate):

Usage: locate.findutils [-d path | --database=path] [-e | -E | --[non-]existing]
      [-i | --ignore-case] [-w | --wholename] [-b | --basename]
      [--limit=N | -l N] [-S | --statistics] [-0 | --null] [-c | --count]
      [-P | -H | --nofollow] [-L | --follow] [-m | --mmap] [-s | --stdio]
      [-A | --all] [-p | --print] [-r | --regex] [--regextype=TYPE]
      [--max-database-age D] [--version] [--help]
      pattern...

The following is the syntax for mlocate:

Usage: locate [OPTION]... [PATTERN]...
Search for entries in a mlocate database.

  -A, --all              only print entries that match all patterns
  -b, --basename         match only the base name of path names
  -c, --count            only print number of found entries
  -d, --database DBPATH  use DBPATH instead of default database (which is
                         /var/lib/mlocate/mlocate.db)
  -e, --existing         only print entries for currently existing files
  -L, --follow           follow trailing symbolic links when checking file
                         existence (default)
  -h, --help             print this help
  -i, --ignore-case      ignore case distinctions when matching patterns
  -l, --limit, -n LIMIT  limit output (or counting) to LIMIT entries
  -m, --mmap             ignored, for backward compatibility
  -P, --nofollow, -H     don't follow trailing symbolic links when checking file
                         existence
  -0, --null             separate entries with NUL on output
  -S, --statistics       don't search for entries, print statistics about each
                         used database
  -q, --quiet            report no error messages about reading databases
  -r, --regexp REGEXP    search for basic regexp REGEXP instead of patterns
      --regex            patterns are extended regexps
  -s, --stdio            ignored, for backward compatibility
  -V, --version          print version information
  -w, --wholename        match whole path name (default)


Summary
Article Name
The Locate command (Linux)
Description
If there is something that is quite vital, on Linux systems in CLI mode (no GUIs, no KDE or Gnome), is to have a simple way to search for specific files/folders on the filesystem. To do this we can install and use the locate utility, on Linux systems.
Author
Publisher Name
Heelpbook.net