How to Locate files in Linux with mlocate

This article show how to locate file easily in Linux. To install and update mlocate so as to use immediately.

$ sudo apt install mlocate
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
Suggested packages:
  nocache
The following NEW packages will be installed:
  mlocate
0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
Need to get 98.3 kB of archives.
After this operation, 517 kB of additional disk space will be used.
Get:1 http://deb.debian.org/debian bullseye/main amd64 mlocate amd64 0.26-5 [98.3 kB]
Fetched 98.3 kB in 0s (558 kB/s)
Selecting previously unselected package mlocate.
(Reading database ... 30418 files and directories currently installed.)
Preparing to unpack .../mlocate_0.26-5_amd64.deb ...
Unpacking mlocate (0.26-5) ...
Setting up mlocate (0.26-5) ...
update-alternatives: using /usr/bin/mlocate to provide /usr/bin/locate (locate) in auto mode
Adding group `mlocate' (GID 114) ...
Done.
Created symlink /etc/systemd/system/timers.target.wants/mlocate.timer → /lib/systemd/system/mlocate.timer.
mlocate.service is a disabled or a static unit, not starting it.
Processing triggers for man-db (2.9.4-2) ...
$ man mlocate

NAME
       locate - find files by name

SYNOPSIS
       locate [OPTION]... PATTERN...

DESCRIPTION
       locate reads one or more databases prepared by updatedb(8) and writes file names matching at
       least one of the PATTERNs to standard output, one per line.

       If --regex is not specified, PATTERNs can contain globbing characters.  If any PATTERN  con‐
       tains no globbing characters, locate behaves as if the pattern were *PATTERN*.

       By  default,  locate does not check whether files found in database still exist (but it does
       require all parent directories to exist if the database was built with  --require-visibility
       no).   locate  can  never  report files created after the most recent update of the relevant
       database.
....
SEE ALSO
       updatedb(8)

So, now it is installed, lets locate something.

$ cd ~/
$ echo "My File!" > mylocatefile.txt
$ locate mylocatefile.txt

ok, so there is an error…

locate: can not stat () `/var/lib/mlocate/mlocate.db': No such file or directory

We must update the database first in order to use it. This is in the man page updatedb:

man updatedb
NAME
       updatedb - update a database for mlocate

SYNOPSIS
       updatedb [OPTION]...

DESCRIPTION
       updatedb creates or updates a database used by locate(1).  If the database already exists, its
       data is reused to avoid rereading directories that have not changed.

$ sudo updatedb

Now we can search for files.

$ locate mylocatefile.txt
/home/ipfs/mylocatefile.txt

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.