When searching for a lost file on a Linux server, most users immediately turn to the powerful find command. However, if you run a command like find / -name "report.txt", Linux literally starts at the very top of the hard drive and manually scans every single folder, one by one, until it finds a match. On a massive server, this can take several minutes and heavily tax the system’s resources. If you simply need to find a file by its name as quickly as possible, you should use the locate command. Unlike find, locate does not scan the hard drive; it instantly searches a pre-built, optimized index database, returning results in milliseconds.
The Basic Syntax
Using locate is incredibly straightforward.
- Open your Linux terminal.
- Type:
locate [filename](e.g.,locate report.txt). - Press Enter.
The terminal will instantly print the absolute path of every file on the system that matches that name (e.g., /home/user/Documents/2023/report.txt).
Wildcards and Partial Matches
The true power of locate is that it assumes you are doing a partial search by default. If you type locate report, it will find “report.txt”, “annual_report.pdf”, and “report_draft.docx”.
If you only want to find files with a specific extension, you can use the asterisk wildcard (*). For example, to instantly find every single PDF file on the entire server, type: locate *.pdf.
The Catch: The updatedb Command
Because locate relies on a pre-built database (the index) rather than scanning the live hard drive, its results are only as accurate as the last time that database was updated. By default, most Linux systems only update this database once a day (usually overnight via a cron job).
The Scenario: You create a new file named new_budget.xlsx at 9:00 AM. At 9:05 AM, you try to find it using locate new_budget.xlsx. The command will return absolutely nothing, because the file is too new to be in the database.
The Solution: You must force Linux to rebuild the database immediately before you search. This requires administrator (root) privileges.
- Type:
sudo updatedb - Press Enter and type your password.
- Wait a few seconds for the database to rebuild.
- Now run your
locatecommand again. The new file will instantly appear in the results.