Website Vidya
Linux & ServersStep-by-Step Guide

locate Command in Linux: Fast Database File Search Guide

Learn locate command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

RR
Rajesh RayLead Systems Educator
Published:
9 min read
PDF Cheat Sheet
locate Command in Linux: Fast Database File Search Guide
AI Executive SummaryWebsiteVidya AI

9 min read

Learn locate command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What locate Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

Searching for files across deep directory trees is a daily requirement for system administrators, and the locate command in linux provides the fastest mechanism for discovering file paths. While tools like find crawl the physical filesystem inode by inode—which can take minutes on large storage volumes—locate searches a pre-built binary index database in milliseconds.

Modern Linux distributions typically ship plocate (post-modern locate) or mlocate (merging locate) to provide this service. A periodic background job or systemd timer (plocate-updatedb.timer) executes the updatedb command, indexing file and directory paths across local filesystems.

Understanding how to trigger manual database refreshes with updatedb, filter searches using case-insensitive flags (-i) and regular expressions (--regex), match basenames strictly (-b), and verify file existence (-e) allows engineers to locate assets instantly without placing I/O stress on production storage.

Advertisement
locate Command in Linux: Fast Database File Search Guide — syntax, flags, and practical terminal workflow diagram
locate Command in Linux: Fast Database File Search Guide — command syntax, key options, and production workflow reference.

What locate Does and When to Use It

Architecturally, locate operates entirely in userspace by querying the binary database located at /var/lib/plocate/plocate.db (or /var/lib/mlocate/mlocate.db). Modern plocate utilizes liburing and an inverted index of trigrams (sequences of three characters) compressed with zstd. When you run locate keyword, plocate searches the trigram index to locate matching candidates and decompresses only the relevant filename blocks, achieving sub-second responses even on filesystems containing tens of millions of files.

The database is generated and refreshed by updatedb(8), which crawls mounted filesystems and writes the index. To protect multi-user system security, mlocate and plocate check file visibility during queries: when an unprivileged user runs locate, the utility inspects the user's permissions and suppresses paths located in directories that the calling user lacks read/execute permissions to view, preventing unauthorized exposure of private files.

At the operating system level, locate (distributed in plocate) interfaces with the Linux kernel through standard C library system calls and virtual filesystems. Understanding how locate resolves file descriptors, kernel structures, and exit status codes helps system administrators predict performance on high-load production servers.

Availability and Installation Across Linux Distributions

The locate utility is packaged in plocate across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:

Advertisement

Before running administrative tasks or automation scripts, verify whether locate is installed and inspect which binary path and version your shell resolves:

type -a locate
locate --version 2>/dev/null || man -f locate

# Illustrative output (reviewed against documentation)
locate is /usr/bin/locate
locate (plocate)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y plocate

# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y plocate

# Arch Linux
sudo pacman -S --noconfirm plocate

# Alpine Linux
sudo apk add --no-cache plocate

Command Syntax, Arguments, and Exit Status Codes

locate [OPTION]... PATTERN... | plocate [OPTION]... PATTERN...

The basic syntax is locate [OPTION]... PATTERN.... The command matches any path in the database containing the specified PATTERN as a substring. If multiple patterns are provided, locate returns paths that match all of the specified patterns.

Crucial flags include -b (--basename), which matches the pattern strictly against the filename component rather than the leading directory path, -i (--ignore-case) for case-insensitive matching, -e (--existing) to check the live filesystem and suppress files that were deleted since the last database update, and -r (--regexp) to evaluate POSIX regular expressions.

  • 0 — Matching files were found and output successfully.
  • 1 — No matching files or directories were found in the database.
  • 2 — Operational error, such as missing database file or invalid command-line option.

Important Options and Flags Reference

Option / FlagLong Form / ArgumentTechnical Behavior and Purpose
-b--basenameMatches only the base filename rather than the full directory path.
-c--countSuppresses output paths and prints only the total number of matching entries.
-d <DB>--database=<DB>Specifies an alternate database file to query instead of the default database.
-e--existingChecks live filesystem and prints only files that currently exist on disk.
-i--ignore-caseIgnores case distinctions when matching patterns.
-l <N>--limit=<N>Limits the number of results printed to at most N entries.
-r--regexp=<REGEXP>Treats the pattern argument as an extended regular expression.
-q--quietSuppresses error messages about unreadable databases or files.

The combination locate -b '\filename' is essential when searching for a common filename like nginx.conf. A naive locate nginx.conf matches every single file located inside any directory containing nginx.conf in its path (e.g. /usr/share/doc/nginx.conf.d/readme.txt). Passing -b restricts matching strictly to the final path segment, returning exact filename hits.

Advertisement

Always pass -e (--existing) during active administrative tasks. Because updatedb runs on a schedule (typically daily), files that were deleted earlier in the day remain present in the database. Adding -e instructs locate to execute a lightweight stat(2) call before printing, ensuring that only currently surviving files are displayed.

When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.

Practical Basic and Advanced Usage Examples

1. Locate Files by Keyword Substring Instantly

Search the pre-indexed database for any file containing a specific keyword.

locate nginx.conf

# Illustrative output (reviewed against documentation)
/etc/nginx/nginx.conf
/usr/share/man/man8/nginx.conf.8.gz

locate scans the database index in milliseconds and returns all matching absolute file paths.

2. Match Base Filename Strictly with -b

Prevent directory path segments from matching and isolate the exact target filename.

locate -b "\passwd"

# Illustrative output (reviewed against documentation)
/etc/passwd
/etc/pam.d/passwd
/usr/bin/passwd

The -b flag and backslash escape force locate to match 'passwd' strictly at the end of the path.

3. Perform a Case-Insensitive Search with -i

Find files regardless of uppercase or lowercase lettering in the filename.

locate -i "readme.md"

# Illustrative output (reviewed against documentation)
/home/admin/project/README.md
/var/www/html/readme.md

The -i flag matches both uppercase README.md and lowercase readme.md cleanly.

4. Filter for Currently Existing Files on Disk with -e

Suppress stale entries for files that have been deleted since the last updatedb index run.

locate -e "temp_debug.log"

The -e flag checks disk inodes; if the file was deleted, it is automatically filtered out.

5. Count Total Matching Files Without Printing Paths with -c

Quickly determine the total number of files matching a pattern across the system.

locate -c "*.png"

# Illustrative output (reviewed against documentation)
1420

The -c flag outputs only the count integer without flooding the terminal with thousands of paths.

6. Update the File Database Manually with updatedb

Force an immediate index refresh so newly created files can be discovered right away.

sudo updatedb
locate "brand_new_file.txt"

# Illustrative output (reviewed against documentation)
/home/admin/brand_new_file.txt

updatedb scans physical filesystems and writes an updated database, making new files searchable instantly.

Real-World Workflows, Pipelines, and Shell Automation

Fast Configuration Audit and Location Discovery Pipeline

When auditing an unfamiliar Linux server, use locate with case-insensitive basename filtering to discover all virtual host configuration files and verify their live existence.

echo "Discovering Nginx and Apache site configurations..."
CONFIG_LIST=$(locate -b -i -e "*.conf" | grep -E "(nginx|apache|httpd)/sites")

echo "Discovered configuration files:"
echo "$CONFIG_LIST"

# Illustrative output (reviewed against documentation)
Discovering Nginx and Apache site configurations...
Discovered configuration files:
/etc/nginx/sites-available/default.conf
/etc/nginx/sites-enabled/default.conf

Combining locate -b -i -e with grep allows instant location of configuration assets without slow filesystem scans.

Automated Package Installation Hook for Updatedb

In automation pipelines, ensure newly deployed binaries and libraries are indexed immediately for developer lookup.

echo "Triggering background updatedb index refresh..."
if command -v plocate-updatedb >/dev/null 2>&1; then
  sudo plocate-updatedb
elif command -v updatedb >/dev/null 2>&1; then
  sudo updatedb
fi
echo "Index refreshed. Verifying binary location:"
locate -b "\python3.12"

# Illustrative output (reviewed against documentation)
Triggering background updatedb index refresh...
Index refreshed. Verifying binary location:
/usr/bin/python3.12

Checks for plocate-updatedb or updatedb and triggers an immediate refresh, verifying the new binary path.

Pipelines, Redirection, Quoting, and Shell Expansion

When embedding locate inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.

Permissions, Security Implications, and Safe Execution

Modern mlocate and plocate implementations enforce file visibility permissions. When an unprivileged user executes locate, the database search filters out paths inside parent directories that the user cannot access, preventing information disclosure of sensitive file names.

The configuration file /etc/updatedb.conf governs which directories and filesystem types are indexed. By default, updatedb excludes network shares (NFS, SMB), virtual filesystems (/proc, /sys), and encrypted mounts to prevent performance degradation and credential exposure.

GNU/Linux, BSD, and BusyBox Implementation Differences

The locate command is not part of POSIX.1-2017; it is an optional utility commonly provided by plocate or mlocate packages on modern Linux distributions (Debian, Ubuntu, RHEL, Fedora, Arch).

On minimal Alpine Linux containers or embedded systems, locate is typically absent to conserve disk space. For portable scripts across all Linux, BSD, and container platforms, use the standard find command.

Troubleshooting Common Errors and Diagnostics

locate: command not found

Root Cause: Neither plocate nor mlocate is installed on the system, which is standard in minimal container images.

Resolution: Install plocate using your distribution's package manager and generate the initial database with updatedb.

sudo apt-get update && sudo apt-get install -y plocate
sudo updatedb

locate cannot find a file that was just created

Root Cause: The file was created after the most recent updatedb indexing run, and the database does not yet know it exists.

Resolution: Run sudo updatedb to force an immediate database refresh, or use find for live filesystem searching.

sudo updatedb
locate myfile.txt

locate: /var/lib/plocate/plocate.db: No such file or directory

Root Cause: The package was installed, but the initial indexing database has not yet been generated.

Resolution: Run updatedb once with root privileges to initialize the database.

sudo updatedb

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
locate queries a pre-indexed database and returns results in milliseconds, but it cannot find files created after the last updatedb run. find searches the live physical filesystem in real time, supporting detailed filters (size, modification time, permissions) at the cost of slower disk traversal.
On most Linux distributions, updatedb runs once daily via a cron job (/etc/cron.daily/plocate) or a systemd timer (plocate-updatedb.timer or mlocate-updatedb.timer).
plocate (post-modern locate) is a modern replacement for mlocate that uses an inverted trigram index compressed with libzstd and io_uring. It is much faster and generates smaller index databases than traditional mlocate.
Edit the /etc/updatedb.conf configuration file. Add directory paths to PRUNEPATHS (e.g. /tmp /var/spool /media) and filesystem types to PRUNEFS (e.g. nfs cifs tmpfs).
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout