Linux pgrep Command Cheat Sheet: How SOC Analysts Hunt Processes Fast
Picture a typical 2 a.m. scenario. A monitoring alert says a web server is making an unusual outbound connection. You SSH in and need the process ID before anything else. You run ps aux | grep python and get a wall of output, including the grep command you just typed. Minutes matter, and you are filtering text by eye.
This is where pgrep earns its place in a Linux threat hunting toolkit. It searches the process table directly and returns clean PIDs. It never matches itself, and its filters (user, parent, session, terminal, age) map closely to the questions analysts ask during SOC incident response. This guide is a practical cheat sheet organized by investigation task rather than alphabet, including a few corrections to commonly circulated cheat sheets.
Table of Contents
- How pgrep Actually Matches Processes
- Matching Basics: Name, Exact Name, Full Command Line
- Filtering by User and Group
- Parent, Session, and Terminal Filters
- Age, State, and Inverse Matching
- Output Formatting Options
- Linux Process Monitoring: An Investigation Workflow
- Using pgrep Safely in Scripts
- Limits and Common Mistakes
- Detection and Hardening Tips
- FAQ
How pgrep Actually Matches Processes
pgrep is part of the procps-ng package on most Linux distributions and reads process information from /proc. By default it treats your search term as an extended regular expression and compares it against the process name. Three details change how you should use it:
- Pattern, not literal.
pgrep sshalso matchessshdand anything else containing "ssh". Use-xwhen you need an exact match. - Names are truncated. The process name pgrep checks by default is the kernel's command name, which Linux limits to 15 characters. Long names can fail to match or collide. Use
-fto match the full command line instead. - Visibility is limited. pgrep only sees what
/procshows your account. Mount options such ashidepid, containers and PID namespaces can all hide processes from you.
Matching Basics: Name, Exact Name, Full Command Line
Start here. These commands cover most day-to-day lookups.
# Find PIDs by process name
pgrep nginx
# Exact name match only
pgrep -x nginx
# PIDs plus process names
pgrep -l nginx
# PIDs plus full command lines
pgrep -a nginx
# Match against the full command line
pgrep -f 'python3.*server.py'
# Full command line match, showing the commands
pgrep -af 'backup.py'
# Case-insensitive match (procps-ng)
pgrep -i nginx
# Match one of several names exactly
pgrep -x 'nginx|apache2'
What to expect: plain pgrep prints one PID per line. With -a, each line shows the PID followed by the full command, which is usually what you want during an investigation because the arguments often reveal intent.
Analyst note: -f is powerful and also the main source of false positives. A pattern like python can match unrelated tools, editors with a Python file open, or your own shell command if you typed the pattern into a wrapper. Always run with -a first and read what you matched.
Filtering by User and Group to Spot Unusual Ownership
Ownership is one of the fastest triage signals. A web service account running an interactive shell deserves a closer look.
# Processes by effective user (name or UID)
pgrep -u alice
# Named process owned by a specific user
pgrep -u www-data nginx
# Processes by real user ID
pgrep -U 1001
# Processes by real group ID
pgrep -G 1002
# Process group ID (not the same as -G)
pgrep -g 5678
Correction worth knowing: -u filters by effective user ID, and -U filters by real user ID. Some circulated cheat sheets label -u 1001 as "real user ID", which is wrong. Likewise, -G is the real group ID, while lowercase -g is the process group ID. The difference matters for setuid binaries, where real and effective IDs differ. That mismatch is itself a useful thing to look for.
Parent, Session, and Terminal Filters for Process Tree Questions
Attack investigations are often about relationships. Which process spawned this one? Is it attached to a terminal? Did it come from an interactive session?
# Children of a specific parent PID
pgrep -P 1234 -a
# Children of a parent, matching an exact name
pgrep -P 1234 -x worker
# Processes in a session
pgrep -s 5678
# Processes attached to a terminal, with commands
pgrep -a -t pts/0
A practical pattern: take the oldest matching web server process (usually the master) and list what it spawned.
pgrep -P "$(pgrep -o -x nginx)" -a
Healthy workers look boring and consistent. A shell, a download utility or an interpreter appearing as a child of a service that should never launch one is worth escalating. Interpret that finding carefully. It is a lead, not proof of compromise.
Age, State, and Inverse Matching
# Oldest and newest matching process
pgrep -o nginx
pgrep -n nginx
# Show names with oldest/newest selection
pgrep -o -l nginx
pgrep -n -l nginx
# Processes at least N seconds old (newer procps-ng versions)
pgrep -O 3600 nginx
# Processes in a given state (R running, S sleeping, T stopped)
pgrep -a -r R
# Everything that does NOT match a pattern
pgrep -v nginx
Age helps when you suspect something started recently. Newest-process selection (-n) is handy right after you trigger an action and want to catch what it launched. Be aware that -O and -r depend on your procps-ng version, so confirm with man pgrep on the host. Also note that -v inverts the match and can return a very long list.
Output Formatting Options
# Count matches
pgrep -c nginx
# Comma-separated PIDs
pgrep -d ',' nginx
# Space-separated PIDs
pgrep -d ' ' nginx
Comma-separated output pairs well with tools that accept a PID list, such as ps -p and top -p.
Linux Process Monitoring: An Investigation Workflow
pgrep finds the process. Other tools tell you what it is doing. Here is a defensive workflow that keeps the steps read-only.
Step 1: Locate and list.
pgrep -a -f 'suspicious_script'
Step 2: Pull process details. This shows the parent PID, owner, state and command name for the oldest exact match.
ps -p "$(pgrep -o -x nginx)" -o pid,ppid,user,stat,comm
Step 3: Inspect open files and network handles.
pid=$(pgrep -n -x nginx)
if [ -n "$pid" ]; then
lsof -p "$pid"
fi
Step 4: Inspect memory mappings.
pid=$(pgrep -n -x nginx)
if [ -n "$pid" ]; then
pmap -x "$pid"
fi
Step 5: Check what binary is really running. Compare the name pgrep shows with the actual executable on disk.
ls -l /proc/PID/exe
Replace PID with the number from step 1. If the link shows a path in a temporary directory, or ends with "(deleted)", the binary was removed after launch. That is a common behavior pattern worth documenting, although some legitimate software updates also produce it. Treat it as a reason to dig further, not as a verdict.
Ownership and nice values (ps -p "$pid" -o pid,ni,pri,comm) add context. A process with an unexpectedly low priority value or an unfamiliar owner may be worth a second look.
Using pgrep Safely in Scripts
pgrep is also a reliable building block for health checks and quick automation.
# Check whether a process exists
if pgrep -x nginx >/dev/null; then
echo "nginx is running"
else
echo "nginx is not running"
fi
# Count matches
count=$(pgrep -c nginx)
echo "Matching processes: $count"
# Save the newest matching PID
pid=$(pgrep -n -x worker)
pgrep sets a clear exit status: 0 when at least one process matched, 1 when none matched. That makes it easy to use directly in if statements.
Race conditions: a PID can vanish between the search and the next command, and PIDs can be reused over time. Always check that the variable is not empty, and expect inspection commands to fail occasionally. In incident work, capture the output immediately and record a timestamp so your notes remain defensible.
Warning on automated actions: pgrep itself only reads. The danger starts when you pipe results into kill or use pkill with a pattern. A broad -f pattern can terminate unrelated processes, including critical services. Preview first:
# Preview exactly what a pattern would match before any action
pgrep -af 'your-pattern'
Only after reviewing that list should you decide on any further step, and in a production incident, follow your team's change and containment procedures rather than killing processes ad hoc.
Limits and Common Mistakes
- Remote command self-match. When you run
ssh host "pgrep -f pattern", the remote shell's own command line contains the pattern and can show up as a match. Use a bracket trick (such as[p]attern) or verify with-a. - Name truncation. Long process names are truncated to 15 characters in the default match. Use
-ffor anything longer. - Treating pgrep as ground truth. It reads
/proc. Malware with kernel-level hiding can conceal processes from user-space tools, so pgrep results should be cross-checked with endpoint telemetry. - Container blind spots. From inside a container you see only that container's PID namespace. From the host you see more, but PIDs differ between views.
- Version differences. Options like
-O,-r,-iand--nsvary by procps-ng version and OS. Confirm withpgrep --versionandman pgrep.
Detection and Hardening Tips for Endpoint Detection and Response Teams
pgrep is a manual tool. Mature teams combine it with continuous visibility.
- Baseline normal. Know which users should own which processes, and what a web server's children normally look like. pgrep is fast for checking against that baseline.
- Collect process execution telemetry. Auditd rules for
execve, or an endpoint detection and response agent, capture what ran even after a process exits. pgrep only sees what is alive right now. - Consider restricting
/procvisibility. Thehidepidmount option can limit users to seeing their own processes. Test it first, because some monitoring agents and tools depend on broader visibility. - Watch for name masquerading. Compare process names with executable paths and parent relationships. Names alone are easy to imitate.
- Document your commands. Save the exact pgrep invocations used during an incident, with timestamps, for the case record.
Expert Tips
- Make
pgrep -afa habit. Seeing arguments catches more than names do. - Prefer
-xwhenever you know the exact name to avoid partial matches. - Use
-cas a quick sanity check before running anything broader. - Combine filters, such as
-u www-data -a, to shrink results before reading them. - Use
pgrep --helpandman pgrepon the target host. Behavior differs across distributions, and the local manual is authoritative. - Use
-ainstead of-lwhen you need arguments. Plain-lshows only the name.
Related Cybersecurity Topics You Should Explore
- Linux pmap Command Cheat Sheet: 40 Examples for Memory Analysis
- Capcom Data Breach: 11.77M Records Exposed – Are You Safe?
- VeloCloud Orchestrator Flaw: Read-Only Login Gives Superuser
- 55 Linux Job Control Commands Every SOC Analyst Should Know
- PHP2Shell Patch Guide: Fix CVE-2026-109618 & 109619 Fast
- FortiSIEM CVE-2026-106173: Public PoC Drops, Patch Now
- Linux renice Command: 54 Examples to Control CPU Priority
- SBI Data Breach Claim: What's Real and What's Not
- Linux nice Command: 30 Examples to Protect Your Server CPU
FAQ
What is the difference between pgrep and ps aux | grep?
pgrep searches the process table directly, excludes itself from results, and returns clean PIDs. The ps and grep pipeline works but is noisier, and it often matches the grep command itself.
How do I make pgrep match only an exact process name?
Use -x, for example pgrep -x sshd. Without it, pgrep treats your term as a pattern and may match longer names.
Why does pgrep -f return unexpected results?
It matches the entire command line, so a broad pattern can hit unrelated processes. Run it with -a to see what matched, and make the pattern more specific.
What is the difference between -u and -U?
The -u option filters by effective user ID, while -U filters by real user ID. They differ for setuid programs.
Can pgrep find hidden malware?
Not reliably. It reads /proc, so it only shows what the operating system exposes. Stealthy threats can evade it, which is why EDR telemetry and memory forensics matter.
Is pgrep safe to run during an incident?
pgrep is read-only, so it does not alter processes. Be careful with pkill or any command that sends signals, and follow your incident response procedures.
Why does pgrep not find my process with a long name?
Default matching uses the kernel command name, which is limited to 15 characters. Use pgrep -f to match against the full command line.
Conclusion
pgrep will not replace full process telemetry, but it answers the first questions of any investigation quickly: what is running, who owns it, what started it, and how long it has been there. Learn the handful of flags covered here, keep -a and -x in your muscle memory, and verify option support on each host. Used with read-only follow-up tools and a healthy respect for false positives, it is one of the most efficient commands in a Linux defender's toolkit.
Analysis based on SOC monitoring experience and review of procps-ng documentation.
