ripgrep Command in Linux: Fast Recursive Search with rg
Learn ripgrep command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
9 min read
Learn ripgrep command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
- What rg Does and When to Use It
- Availability and Installation Across Linux Distributions
- Command Syntax, Arguments, and Exit Status Codes
Adopting the ripgrep command in linux has transformed how software engineers and systems administrators perform recursive code and log searches across modern environments. Written in Rust by BurntSushi (Andrew Gallant), ripgrep combines world-class execution speed with sensible developer-first defaults, automatically ignoring binary files, hidden files, and patterns listed in .gitignore.
The ripgrep command in Linux (invoked as rg) is a line-oriented search tool that recursively searches directory trees for regular expressions while respecting .gitignore rules by default. Run rg 'pattern' to search the current directory, rg -i 'pattern' for case-insensitive search, or rg -t py 'pattern' to restrict searches strictly to Python source files.
While traditional grep remains a universal standard on minimal Unix hosts, ripgrep routinely outperforms it by a factor of 5 to 10 on multi-core hardware. It achieves this by combining multi-threaded directory traversal, SIMD-accelerated string search algorithms, and memory-mapped file I/O into a robust, memory-safe binary.
Beyond raw performance, ripgrep features an ergonomic interface: it colorizes output by default, provides built-in file-type filtering (-t), supports PCRE2 lookarounds and backreferences, and integrates seamlessly into terminal editors like Neovim and modern terminal workflows.
What rg Does and When to Use It
Under the hood, ripgrep's exceptional speed stems from the Rust regex crate and its specialized ignore crate. When searching for literal strings or regex patterns with fixed prefixes, ripgrep employs the Teddy algorithm—a SIMD-accelerated multi-byte vector searching routine utilizing AVX2 or SSE4.2 CPU instruction sets to search multiple bytes per processor cycle.
For file discovery, ripgrep spawns a parallel thread pool that simultaneously traverses directory trees using the walkdir and ignore crates. As directory entries are read via getdents64(2), ripgrep checks them against .gitignore and .ignore rules in parent directories. File search workers read files using either raw read(2) syscalls or memory-mapped I/O (mmap(2)), automatically choosing memory-mapping for large files on 64-bit systems while falling back to buffered streaming for stdin and small files.
Under the hood, rg gathers runtime telemetry or dispatches control signals by reading virtual filesystems mounted at /proc and /sys, or by communicating with PID 1 (systemd) over D-Bus. Using flags such as -i, -S, -t, -T turns raw process and service tables into actionable diagnostics during incident response.
Availability and Installation Across Linux Distributions
The rg utility is packaged in ripgrep 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:
Before running administrative tasks or automation scripts, verify whether rg is installed and inspect which binary path and version your shell resolves:
type -a rg
rg --version 2>/dev/null || man -f rg
# Illustrative output (reviewed against documentation)
rg is /usr/bin/rg
rg (ripgrep)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y ripgrep
# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y ripgrep
# Arch Linux
sudo pacman -S --noconfirm ripgrep
# Alpine Linux
sudo apk add --no-cache ripgrep
Command Syntax, Arguments, and Exit Status Codes
rg [OPTIONS] PATTERN [PATH...]
The basic invocation structure is rg [OPTIONS] PATTERN [PATH...]. If no PATH is specified, ripgrep automatically searches the current working directory recursively. Unlike grep, you do not need to pass -r or -R to search subdirectories; recursion is the default behavior.
ripgrep uses standard Rust regular expression syntax by default, which is largely compatible with Perl-compatible regular expressions (PCRE) while guaranteeing linear worst-case matching time (O(mn)). For advanced features like lookaround assertions and backreferences, passing the -P (--pcre2) flag activates the PCRE2 engine.
0— One or more matches were found across evaluated files.1— No matches were found across any evaluated files.2— An error occurred; invalid regex, unrecognized flag, or I/O failure.
Important Options and Flags Reference
| Option / Flag | Long Form / Argument | Technical Behavior and Purpose |
|---|---|---|
-i | --ignore-case | Case-insensitive search across all inputs. |
-S | --smart-case | Searches case-insensitively if pattern is all lowercase; case-sensitively if it contains uppercase. |
-t | --type=TYPE | Search only files matching the TYPE classification (e.g. -t py, -t js, -t rust). |
-T | --type-not=TYPE | Do not search files matching the TYPE classification. |
-u | --unrestricted | Reduce filtering: -u searches .gitignored files; -uu searches hidden files; -uuu searches binary files. |
-w | --word-regexp | Only match patterns surrounded by word boundaries. |
-l | --files-with-matches | Print only the paths of files that contain at least one match. |
-C | --context=NUM | Show NUM lines before and after each matching line. |
-g | --glob=GLOB | Include or exclude files matching the given glob (prefix with ! to exclude). |
The -S (--smart-case) option is one of ripgrep's most popular workflow enhancements: searching for rg -S 'status' matches 'status', 'Status', and 'STATUS', while rg -S 'Status' matches only 'Status'.
The -u (--unrestricted) flag operates in three distinct tiers: a single -u disables .gitignore filtering; -uu disables both .gitignore and hidden file/directory filtering (searching dotfiles like .env); and -uuu additionally disables binary file filtering, effectively reverting ripgrep to the behavior of standard grep -a.
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. Basic Recursive Search in Current Directory Tree
Search for a function name across all files in the current repository, automatically skipping git metadata.
rg "authenticateUser"
# Illustrative output (reviewed against documentation)
src/auth/service.ts
24:export async function authenticateUser(credentials: Credentials) {
88: const session = await authenticateUser(req.body);
ripgrep automatically searches subdirectories, formats output with file paths and line numbers, and ignores node_modules and .git.
2. Case-Insensitive Search Using Smart Case (-S)
Leverage smart-case searching to automatically adapt matching based on pattern casing.
rg -S "rabbitmq_password"
# Illustrative output (reviewed against documentation)
config/production.env
18:RABBITMQ_PASSWORD="production_super_secret"
config/local.env
14:rabbitmq_password="guest"
Because the search pattern is all lowercase, -S searches case-insensitively, matching both lowercase and uppercase definitions.
3. Restrict Search to Specific Programming Language File Types
Search for database queries exclusively within Python files using built-in file types.
rg -t py "SELECT * FROM" /opt/project/
# Illustrative output (reviewed against documentation)
/opt/project/services/billing.py:42: query = "SELECT * FROM transactions WHERE user_id = %s"
/opt/project/services/users.py:18: cursor.execute("SELECT * FROM users WHERE active = 1")
The -t py flag instructs ripgrep to evaluate only files with extensions recognized as Python (.py, .pyw, etc.).
4. List All Supported Built-In File Types
View the comprehensive list of predefined file type aliases available for the -t flag.
rg --type-list | head -n 6
# Illustrative output (reviewed against documentation)
agda: *.agda, *.lagda
aidl: *.aidl
amake: *Makefile.am, *amake.srclist
ansible: *hosts, *.inventory
applescript: *.applescript, *.scpt
asm: *.asm, *.s, *.S
ripgrep includes hundreds of built-in file type mappings out of the box.
5. Include Ignored and Hidden Files with Unrestricted Mode
Search for an API key across all files, including .env files and directories listed in .gitignore.
rg -uu "STRIPE_SECRET_KEY"
# Illustrative output (reviewed against documentation)
.env:14:STRIPE_SECRET_KEY="sk_live_XXXXXXXXXXXXXXXXXXXX"
.env.staging:14:STRIPE_SECRET_KEY="sk_test_YYYYYYYYYYYYYYYYYYYY"
Passing -uu disables both .gitignore parsing and hidden dotfile suppression.
6. Custom Glob Filtering for Targeted Directory Exclusions
Search for a token while excluding test folders and matching only TypeScript files.
rg "processOrder" -g "*.ts" -g "!tests/**"
# Illustrative output (reviewed against documentation)
src/controllers/order.ts:54: await processOrder(cart);
src/workers/queue.ts:102: processOrder(job.data);
Glob expressions prefixed with an exclamation mark (!) act as exclusion patterns.
Real-World Workflows, Pipelines, and Shell Automation
Incident Response: Rapid Root-Cause Analysis Across Gigabytes of Logs
Quickly pinpoint critical errors across distributed microservice log files on a production host.
#!/usr/bin/env bash
set -euo pipefail
LOG_DIR="/var/log/containers"
echo "Searching container logs for fatal exceptions..."
rg -n -C 1 --no-heading --max-count 3 \
-g "*.log" \
-e "FATAL|PANIC|OutOfMemory" "$LOG_DIR"
# Illustrative output (reviewed against documentation)
/var/log/containers/auth-77f-94.log:412-2026-10-22T14:10:02Z INFO Healthcheck OK
/var/log/containers/auth-77f-94.log:413:2026-10-22T14:10:05Z FATAL DB connection pool exhausted
/var/log/containers/auth-77f-94.log:414-2026-10-22T14:10:05Z INFO Terminating process
ripgrep parallelizes across all available CPU cores, parsing compressed and uncompressed log files in fractions of a second.
Monorepo Refactoring: Renaming Exported Symbols Safely
Find all usages of a deprecated JavaScript component across a massive monorepo before migration.
#!/usr/bin/env bash
set -euo pipefail
COMPONENT="OldDataTable"
echo "Auditing usages of <$COMPONENT />..."
TOTAL_USAGES=$(rg -c -t js -t ts -t tsx -w "$COMPONENT" | awk -F: '{s+=$2} END {print s}')
echo "Total occurrences found: $TOTAL_USAGES"
echo "Affected files:"
rg -l -t js -t ts -t tsx -w "$COMPONENT"
# Illustrative output (reviewed against documentation)
Auditing usages of <OldDataTable />...
Total occurrences found: 18
Affected files:
src/pages/Dashboard.tsx
src/pages/Inventory.tsx
src/components/ReportView.tsx
Combining rg -c and rg -l with type filtering gives developers instant impact analysis before executing refactoring passes.
Pipelines, Redirection, Quoting, and Shell Expansion
When embedding rg 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
ripgrep is strictly a read-only search tool. However, passing ripgrep output directly to xargs or sed without null-byte separators can inadvertently modify the wrong files if file paths contain spaces or newlines. Always use rg --null with xargs -0.
ripgrep respects local .ignore and .rgignore files. In shared or multi-tenant hosting environments, ensure untrusted users cannot place malicious .ignore files in directories being audited by security tools, as this could cause ripgrep to silently skip backdoor files.
When running ripgrep against untrusted user-supplied search patterns, consider that regular expression complexity is protected by the Rust regex crate's guaranteed linear-time engine (avoiding catastrophic ReDoS). However, enabling PCRE2 with -P disables this guarantee and could permit regex denial-of-service.
GNU/Linux, BSD, and BusyBox Implementation Differences
ripgrep is packaged as rg across modern distributions: apt install ripgrep on Ubuntu/Debian, dnf install ripgrep on Fedora/RHEL, and pacman -S ripgrep on Arch Linux. On Alpine Linux, it is available via apk add ripgrep.
Unlike grep, ripgrep is not a POSIX utility and is rarely installed by default on minimal base Docker images or embedded systems. Shell scripts intended for universal deployment across arbitrary Linux servers should check for rg availability and fall back to grep -rn if absent.
Troubleshooting Common Errors and Diagnostics
ripgrep returns no results for a file known to exist
Root Cause: The target file is listed in .gitignore, begins with a dot (hidden file), or is recognized as binary by ripgrep's automated MIME detection.
Resolution: Pass -u (to search .gitignored files), -uu (to include hidden files), or -uuu (to include binary files).
rg -uu "search_term" path/to/file
Lookaround or backreference syntax error in regex
Root Cause: The Rust regex engine used by default in ripgrep does not support lookaheads (?=), lookbehinds (?<=), or backreferences (\1) in order to guarantee linear-time execution.
Resolution: Enable the PCRE2 regex engine by passing the -P (--pcre2) flag.
rg -P "(?<=user_id=)[0-9]+" /var/log/app.log
Command 'rg' not found after installing ripgrep
Root Cause: The package was installed via cargo or a custom tarball into ~/.cargo/bin or /usr/local/bin, which is not in the current shell's PATH.
Resolution: Add ~/.cargo/bin to your PATH in ~/.bashrc, or install via system package manager.
export PATH="$HOME/.cargo/bin:$PATH"
Alternatives, Related Commands, and Related Tutorials
- Grep Command in Linux: Search Text, Files, and Directories — Practical syntax, flags, and examples for
grep. - Grep Multiple Patterns: Match Strings, Words, and Regex in Linux — Practical syntax, flags, and examples for
grep. - Grep Exclude: Exclude Files, Directories, and Patterns in Linux — Practical syntax, flags, and examples for
grep. - awk Command in Linux: Syntax, Text Patterns, and Field Processing — Practical syntax, flags, and examples for
awk. - 25 Best Linux Commands Every Sysadmin Should Know — Core command-line utilities for daily Linux server administration.
- How to Find a File in Linux from the Command Line — Practical file search patterns across Linux directories.
- Linux Commands Knowledge Hub (#linux-commands) — Browse all Linux command-line tutorials and system administration references.
Authoritative References and Official Documentation

The Linux Command Line, 2nd Edition: A Complete Introduction
Frequently Asked Questions
Quick answers to common questions and configurations
~/.bashrc for lightning-fast interactive file fuzzy finding.Editorial Disclosure: Website Vidya is supported by our readers. When you purchase hosting, tools, or software through our verified partner links, we may earn an affiliate commission at no extra cost to you. We only recommend solutions we trust and rigorously verify.
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.
Most Read Guides
TrendingUbuntu Server Not Booting? 10 Simple Steps to Fix It Fast
How to Create a 3D Button in HTML and CSS: Easy Steps
How to Install Python and Pip on Ubuntu 24.04 LTS
How to Install Nginx on Ubuntu 24.04
How to Install Python on Ubuntu 24.04 LTS
Related Technical Guides
Tested runbooks, server administration walkthroughs, and troubleshooting guides





Join the Conversation & Perspective
Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.
No comments on this guide yet. Be the first to share your thoughts or ask a question!