The pgrep command searches running processes and prints matching PIDs.
It is safer and cleaner than parsing ps output with grep in many cases.
Overview
You can match by:
- Process name
- Full command line
- User
- Parent PID
- Terminal
Syntax
pgrep [options] pattern
Command Quick Reference
| Command | Purpose |
|---|---|
pgrep nginx |
Find PIDs with name matching nginx |
pgrep -x nginx |
Exact name match |
pgrep -f "python app.py" |
Match full command line |
pgrep -u root |
Match processes owned by root |
pgrep -af nginx |
Show PID and full command |
Core Workflows
Find PID by Name
pgrep sshd
pgrep -x sshd
Match Full Command Line
pgrep -f "node server.js"
Include Process Details
pgrep -af nginx
This prints PID and command line, which helps validate matches.
Restrict by User
pgrep -u www-data -af php-fpm
Useful Options
| Option | Meaning |
|---|---|
-f |
Match against full command line |
-x |
Require exact process name match |
-a |
Print full command line with PID |
-u |
Match by effective user ID/name |
-P |
Match by parent PID |
-n |
Only newest matching process |
-o |
Only oldest matching process |
Examples
pgrep -af nginx
pgrep -u root sshd
pgrep -n -f "python worker.py"
Troubleshooting
Too Many Matches
Tighten criteria with -x, -u, or a more specific -f pattern.
No Matches Found
- Confirm process is running with
ps aux. - Try
-fif command name differs from executable name. - Check user context with
-u.
Best Practices
- Prefer
pgrepoverps | grepin scripts. - Use
-awhen validating patterns interactively. - Combine with
killonly after confirming the matched command lines. - Use
-xfor exact service names where possible.
Related Commands
pkill: Signal matching processes directlyps: Inspect process table detailskill: Signal specific PIDs