locate – quickly find files in Linux

locate command

Today I’d like to show you one more option you have when searching for files in Linux. If you have a locate tool installed, you’ll be able to find any file almost instantly.

How Does locate Command Work?

locate uses a pretty simple principle – instead of going through your filesystem directory tree every time you need a certain file found, it consults a database which stores locations of most files in your system. The locate database (locatedb) is updated nightly with a separate command. The update occurs during night hours when peak usage of your system is very unlikely, but this means that using such a database through the day will provide instant results.

There is obviously a chance that some files will be moved or even deleted by the time you look for them, then the locate database will still have entries for them and show them in results, but the actual files will be gone. There’s a special command line option for the locate command to only return results for the existing files.

In short, the not-100%-accurate results are definitely worth the amazing speed increase you’ll get when comparing the locate command against a more traditional find command approach to locating files in Unix.

Using locate to Find Files

Simply specify the partial name of a file you need and watch results appear on your screen in a fraction of a second!

In this example, I’m looking for everything that contains apache2 in its name (note how both files and directories are found):

ubuntu# locate apache2 | more

Report Only Existing Files with locate

If you’re concerned that some of the files you’re looking for could have been moved or deleted since last update of the locatedb database, use the -e command line option:

Report Non-existing Files with locate

Perhaps more useful way to approach the existing/non-existing files with locate is to use -E option which only shows the files which are referred in the locatedb database, but no longer exist.

For example, if I rename one of the files like this:

ubuntu# mv /etc/apache2/apache2.conf.bak /etc/apache2/apache2.conf.backup

And then run the locate -E, it will immediately highlight it:

ubuntu# locate -E apache2 | more

See Also