pgrep Command in Linux: Find and Filter Running Processes by Name
Learn pgrep command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
10 min read
Learn pgrep command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.
- What pgrep Does and When to Use It
- Availability and Installation Across Linux Distributions
- Command Syntax, Arguments, and Exit Status Codes
Interactive Builder for this Guide
Build your custom find syntax (pgrep Command in Linux: Find and Filter Running Processes by Name)
find /var/log -maxdepth 4 -type f -name '*.log' -size +50M -mtime +14 -exec ls -lh {} +/var/logStarting root directory to traverse-maxdepth 4Descend at most 4 directory levels-type fMatch only regular files-name '*.log'Filter filename glob (case-sensitive)-size +50MMatch files larger than 50M-mtime +14Modified more than 14 days ago-exec ls -lh {} +Batch matched paths cleanly into ls -lhUsing the pgrep command in linux is the clean, modern replacement for the classic ps aux | grep pattern | grep -v grep | awk '{print $2}' anti-pattern. While piping ps into grep spawns multiple subshells and frequently matches the grep process itself unless workarounds are used, pgrep scans /proc directly and never matches its own PID.
The pgrep command in Linux searches the running process table using Extended Regular Expressions and attribute filters (such as user, parent PID, terminal, or process age) and prints matching Process IDs (PIDs) to standard output. Use pgrep -a <pattern> to display full command lines alongside PIDs, or pgrep -u <user> to list all processes owned by a specific user.
Provided by the procps-ng package alongside pkill, pgrep prints one matching PID per line by default and exits with status 0 if at least one process matched or 1 if none matched. With a couple of flags—most notably -l (show process name) and -a (show full command line)—it transforms from a minimal PID extractor into a fast process inspection tool.
Because pgrep supports compound filtering by effective UID (-u), real UID (-U), group (-G), parent PID (-P), process group (-g), controlling terminal (-t), and Linux cgroup/namespace attributes, it is indispensable for writing reliable shell scripts and monitoring probes.
What pgrep Does and When to Use It
When pgrep executes, it opens the /proc directory stream via opendir("/proc") and iterates through each numeric task directory. To maximize speed, it first checks lightweight numeric metadata (UID, GID, PPID, PGRP, SID) from stat(2) on /proc/PID and /proc/PID/stat before reading /proc/PID/cmdline.
Just like its sibling pkill, pgrep matches your POSIX Extended Regular Expression against the 15-character kernel task name (comm) by default. Passing -f instructs pgrep to read up to 4 KB+ of null-separated arguments from /proc/PID/cmdline, join them with spaces, and evaluate the regular expression against the complete command string.
Under the hood, pgrep 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 -a, -l, -f, -x turns raw process and service tables into actionable diagnostics during incident response.
Availability and Installation Across Linux Distributions
The pgrep utility is packaged in procps 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 pgrep is installed and inspect which binary path and version your shell resolves:
type -a pgrep
pgrep --version 2>/dev/null || man -f pgrep
# Illustrative output (reviewed against documentation)
pgrep is /usr/bin/pgrep
pgrep (procps)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y procps
# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y procps-ng
# Arch Linux
sudo pacman -S --noconfirm procps-ng
# Alpine Linux
sudo apk add --no-cache procps-ng
Command Syntax, Arguments, and Exit Status Codes
pgrep [OPTIONS] [PATTERN]
The command syntax is pgrep [OPTIONS] [PATTERN]. You can supply a regex pattern alone (pgrep nginx), attribute filters alone (pgrep -u postgres), or both together (pgrep -u postgres -f walwriter). When multiple distinct filter flags are combined, a process must satisfy all conditions (logical AND) to be printed.
By default, each matching PID is separated by a newline (\n). You can customize the output delimiter with -d SEP (for example, pgrep -d, nginx for comma-separated PIDs or pgrep -d' ' nginx for space-separated PIDs), or suppress PID listing altogether and print only the total match count using -c (--count).
0— Successful execution with no runtime or permission errors.1— Operational failure, unmatched condition, or permission restriction.2— Invalid command-line option or malformed syntax.
Important Options and Flags Reference
| Option / Flag | Long Form / Argument | Technical Behavior and Purpose |
|---|---|---|
-a | --list-full | Prints both the numeric PID and the complete command line with all arguments for each matching process. |
-l | --list-name | Prints both the numeric PID and the short process binary name alongside each match. |
-f | --full | Matches the regular expression pattern against the full command line rather than only the 15-character process name. |
-x | --exact | Requires the pattern to match the entire process name (or entire command line when combined with -f). |
-u | --euid EUID,... | Filters matches to processes running under the specified effective user IDs or usernames. |
-P | --parent PPID,... | Lists only child processes whose immediate Parent Process ID equals PPID. |
-c | --count | Suppresses normal PID output and prints only the total count of matching processes. |
-n / -o | --newest / --oldest | Returns only the single most recently started (-n) or earliest started (-o) matching process. |
-v | --inverse | Inverts the match, selecting all processes that do NOT satisfy the specified pattern or filter. |
The single most useful flag combination for interactive troubleshooting is pgrep -fa <pattern>: -f searches across all command-line flags and script paths, while -a prints the full command line next to each PID so you immediately see what each process is doing.
Note the difference between pgrep -l and pgrep -a: in modern procps-ng, -l prints only the short binary name (e.g., 18420 python3), whereas -a prints the full argument string (e.g., 18420 python3 /opt/app/worker.py --port 8080).
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. Search Processes and Display Full Command Lines (-fa)
Use -f to match against full command-line arguments and -a to print both the PID and full command string.
pgrep -fa "nginx|php-fpm"
# Illustrative output (reviewed against documentation)
1104 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
1180 php-fpm: master process (/etc/php/8.3/fpm/php-fpm.conf)
29410 nginx: worker process
29411 nginx: worker process
29450 php-fpm: pool www
29451 php-fpm: pool www
Because pgrep uses Extended Regular Expressions, the pipe operator (|) matches either nginx or php-fpm in a single scan of /proc.
2. List All Processes Owned by a Specific User (-u -l)
Filter the process table by effective username (-u) and display each PID alongside its binary name (-l).
pgrep -u www-data -l
# Illustrative output (reviewed against documentation)
29410 nginx
29411 nginx
29450 php-fpm8.3
29451 php-fpm8.3
When -u is supplied, the pattern argument is optional; pgrep returns every process running under the www-data user.
3. Count the Number of Running Worker Processes (-c)
Pass -c (--count) to output the exact integer count of matching processes for capacity monitoring or health checks.
pgrep -c -u www-data -x nginx
# Illustrative output (reviewed against documentation)
2
This command counts only processes owned by www-data whose exact name is nginx (the 2 worker processes, excluding the root-owned master process).
4. Find the Oldest Master Process or Newest Worker Process (-o and -n)
Identify the original parent/master process with -o (--oldest) or the most recently forked child with -n (--newest).
echo "Oldest (Master) PID:"
pgrep -o -a nginx
echo "Newest (Worker) PID:"
pgrep -n -a nginx
# Illustrative output (reviewed against documentation)
Oldest (Master) PID:
1104 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
Newest (Worker) PID:
29411 nginx: worker process
Because a pre-forking daemon starts its master process before spawning workers, pgrep -o reliably selects the master PID.
5. List All Child Processes of a Parent PID (-P)
Pass a master daemon's PID to -P to list every direct child worker it has spawned.
MASTER_PID=$(pgrep -o -x nginx)
pgrep -P "$MASTER_PID" -a
# Illustrative output (reviewed against documentation)
29410 nginx: worker process
29411 nginx: worker process
First pgrep -o -x nginx finds the master PID (1104), and then pgrep -P 1104 lists all child workers whose PPID is 1104.
6. Format Output with Custom Delimiters (-d) to Feed into ps or top
Join matching PIDs with commas using -d ',' so you can pass them directly to ps -p or top -p.
ps -o pid,ppid,%cpu,%mem,rss,comm -p "$(pgrep -d ',' 'nginx|postgres')"
# Illustrative output (reviewed against documentation)
PID PPID %CPU %MEM RSS COMMAND
984 1 0.1 1.8 74216 postgres
1104 1 0.0 0.2 8920 nginx
29410 1104 0.4 0.3 12440 nginx
29411 1104 0.3 0.3 12180 nginx
Using pgrep -d ',' inside command substitution builds a clean comma-separated list (984,1104,29410,29411) required by ps -p.
Real-World Workflows, Pipelines, and Shell Automation
Worker Pool Minimum-Threshold Watchdog Script
Monitor a background queue consumer pool using pgrep -c -f and trigger a service restart or alert if the active worker count drops below the expected minimum.
#!/usr/bin/env bash
set -euo pipefail
MIN_WORKERS=4
ACTIVE_WORKERS=$(pgrep -c -f "celery.*worker" || true)
echo "Active Celery workers: $ACTIVE_WORKERS (Minimum required: $MIN_WORKERS)"
if [ "$ACTIVE_WORKERS" -lt "$MIN_WORKERS" ]; then
echo "[WARN] Worker count below threshold! Restarting celery.service..." >&2
sudo systemctl restart celery.service
fi
# Illustrative output (reviewed against documentation)
Active Celery workers: 4 (Minimum required: 4)
Note the '|| true' guard: when pgrep -c finds 0 matches, it prints '0' to stdout AND returns exit status 1, which would otherwise trip 'set -e'.
Find Processes Running Older Than a Specific Duration (--older)
On modern procps-ng systems, combine pgrep with ps etimes to detect stuck cron jobs that have been running longer than 1 hour (3600 seconds).
#!/usr/bin/env bash
set -euo pipefail
PIDS=$(pgrep -d ',' -f "/opt/scripts/hourly-report.sh" || true)
if [ -n "$PIDS" ]; then
ps -o pid,etimes,user,args -p "$PIDS" | awk 'NR==1 || $2 > 3600'
else
echo "No hourly-report.sh processes currently running."
fi
# Illustrative output (reviewed against documentation)
PID ELAPSED USER COMMAND
19204 5412 appuser /bin/bash /opt/scripts/hourly-report.sh --env=prod
pgrep locates all candidate script PIDs without self-matching, and ps -o etimes reports elapsed wall-clock runtime in seconds so awk can flag hung jobs.
Pipelines, Redirection, Quoting, and Shell Expansion
When embedding pgrep 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
pgrep is a strictly read-only command that only queries /proc and prints PIDs; however, always verify its output before feeding $(pgrep ...) into destructive commands like kill -9.
Like other /proc utilities, pgrep respects Linux kernel hidepid mount options. On systems where /proc is mounted with hidepid=2, non-root users running pgrep will only see processes belonging to their own UID.
Avoid embedding untrusted user input directly into a pgrep regex pattern in privileged scripts without sanitizing regex metacharacters (such as .* or |), especially if the resulting PIDs are passed to kill.
GNU/Linux, BSD, and BusyBox Implementation Differences
pgrep is widely portable across Linux, FreeBSD, OpenBSD, NetBSD, Solaris, and macOS.
One important portability caveat: on Linux (procps-ng), pgrep -a displays the full command line and pgrep -l displays only the short process name. On macOS and FreeBSD, -a means 'include ancestor processes' and pgrep -fl is used to print the full command line.
Troubleshooting Common Errors and Diagnostics
pgrep -c returns exit status 1 and aborts a script running with set -e when count is 0
Root Cause: By design, pgrep exits with code 1 whenever zero processes match, even when -c (--count) prints '0'.
Resolution: Append '|| true' inside command substitution: COUNT=$(pgrep -c pattern || true).
COUNT=$(pgrep -c -x mydaemon || true)
echo "Count is: $COUNT"
pgrep fails to match a process whose binary name is longer than 15 characters
Root Cause: The Linux kernel stores at most 15 characters in /proc/PID/comm, which is what pgrep searches when -f is omitted.
Resolution: Pass the -f (--full) flag so pgrep searches /proc/PID/cmdline instead.
pgrep -fa "very_long_daemon_name"
pgrep -l only prints the binary name without arguments
Root Cause: In procps-ng 3.3+, -l prints only the short command name while -a (--list-full) prints the full argument vector.
Resolution: Use pgrep -a (or pgrep -fa) to see complete command-line arguments.
pgrep -fa python3
Alternatives, Related Commands, and Related Tutorials
- pkill Command in Linux: Stop Processes by Name, User, and Pattern — Practical syntax, flags, and examples for
pkill. - pidof Command in Linux: Find Process IDs by Program Name — Practical syntax, flags, and examples for
pidof. - How to Kill a Process in Linux: kill, killall, and pkill Guide — Practical syntax, flags, and examples for
kill. - ps Command in Linux: ps aux, ps -ef, Custom Columns, and Sorting — Practical syntax, flags, and examples for
ps. - 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
/proc directly in a single process, never matches itself (eliminating the need for grep -v grep), exits with a clean 0/1 status code for if-statements, and supports native filtering by user (-u), parent PID (-P), and process age (-n/-o).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!