pgrep

On this page 7

pgrep is a Linux command-line utility that looks up running processes by name or other attributes and prints the process IDs (PIDs) of every match. It belongs to the procps (procps-ng) package, the same toolset that provides ps, pkill and top, and it is the standard way to answer the question “which processes match this pattern?” without parsing the output of ps by hand.

In Linux process management, pgrep is the read-only counterpart of pkill: both share the same matching engine, but pgrep only reports what it finds, while pkill sends a signal to the matches. This makes pgrep the safe first step before any action that changes process state, and a frequent building block in shell scripts, service checks and monitoring jobs.

How pgrep finds matching processes

pgrep works by scanning the /proc filesystem, where the kernel exposes one directory per running process. For each numeric directory, it reads files such as stat, status and cmdline to learn the process name, owner, parent, session and start time, then compares those values with the criteria given on the command line.

By default, the pattern is an extended regular expression matched against the process name, which the kernel stores in the comm field. This name is truncated to 15 characters, a limit inherited from the kernel’s task structure. A process started as /usr/local/bin/backup-orchestrator therefore appears as backup-orchestr, and a pattern that relies on the full name will not match unless the -f option is used to search the full command line instead.

When several criteria are given, pgrep combines them with a logical AND: a process must satisfy every option to be listed. The pgrep process itself is always excluded from the results, which avoids the classic mistake of a search command finding its own entry.

The following table summarizes the sources of data that pgrep consults and what each one contributes to matching.

Source in /procInformation obtainedUsed by options
/proc/PID/statName, state, parent PID, session, start timeDefault pattern, -P, -s, -n, -o
/proc/PID/statusReal and effective user and group IDs-u, -U, -G
/proc/PID/cmdlineFull command line with arguments-f, -a
/proc/PID/ns/*Namespace identifiers--ns, --nslist
/proc/PID/cgroupControl group membership--cgroup
Data that pgrep reads for each process

Key pgrep options and output formats

pgrep provides selection options that narrow which processes match and output options that change what is printed. Selection options can filter by user, group, parent, terminal, session, age, namespace or cgroup, so administrators rarely need to post-process the result with other tools.

The table below lists the options that appear most often in administration work, with their effect and a typical use.

OptionEffectTypical use
-fMatches the full command lineFinding a script run by an interpreter
-xRequires an exact name matchAvoiding partial matches such as sshd-session
-u userFilters by effective userListing one account’s processes
-P ppidFilters by parent PIDFinding children of a supervisor
-n / -oSelects only the newest or oldest matchLocating the master or latest worker
-l / -aPrints the name or full command lineVerifying matches before acting
-cPrints only the number of matchesCounting worker processes
-d delimSets the output delimiterProducing a comma-separated PID list
-vInverts the matchListing everything except one program
Frequently used pgrep options

The exit status is an important part of the output. pgrep returns 0 when at least one process matches, 1 when nothing matches, 2 for a syntax error and 3 for a fatal error. Scripts commonly use this status directly in conditions, for example if pgrep -x nginx >/dev/null; then ..., instead of inspecting the printed PIDs.

pgrep compared with ps, pidof and pkill

pgrep overlaps with several neighboring tools in the Processes topic, and choosing the right one depends on whether you need a report, a PID list or an action. ps produces a detailed, formatted snapshot of the process table, pidof returns PIDs for an exact program name, and pkill and killall send signals to matching processes.

The comparison below shows where each tool fits and where it falls short.

ToolMain purposeMatching methodChanges process state
pgrepList PIDs of matching processesRegex on name or command line plus attributesNo
psReport detailed process informationSelection flags, no regexNo
pidofReturn PIDs of a named programExact program nameNo
pkillSignal matching processesSame engine as pgrepYes
killallSignal all processes with a nameExact name by defaultYes
Process lookup tools in Linux

A long-standing anti-pattern is the pipeline ps aux | grep name | grep -v grep | awk '{print $2}'. It is fragile and slower: it matches text anywhere in the line, including user names and arguments, and it depends on column layout. pgrep replaces the whole chain with one precise call that matches structured fields.

Using pgrep safely in scripts and administration

pgrep is most valuable when it is used with anchored patterns and explicit filters. A bare pattern such as pgrep java matches any process whose name contains that substring, which on a busy server can include unrelated tools. Adding -x, -u or ^...$ anchors makes the result predictable and repeatable.

The decision table below maps common administration tasks to a recommended pgrep form.

SituationRecommended commandReason
Check that a daemon is runningpgrep -x sshdExact name avoids partial matches
Find a Python script by namepgrep -f 'python3 .*report.py'Interpreter name hides the script
List a user’s shellspgrep -u alice -l bashCombines user and name filters
Find the main web server processpgrep -o -x nginxOldest match is usually the master
Count application workerspgrep -c -f gunicornPrints a number for monitoring
Preview a pkill targetpgrep -a -f patternShows exactly what would be signaled
Choosing a pgrep form for common tasks

A sound habit is to run pgrep with the same arguments before pkill and read the listed command lines. Because both tools share the matching logic, the pgrep output is an accurate preview of the signal targets, which prevents accidentally terminating a database or an SSH session.

Limitations and common mistakes with pgrep

pgrep reports a snapshot of a changing system, so its result can become stale within milliseconds. A process may exit, or its PID may be reused by a new process, between the moment pgrep prints it and the moment another command acts on it. For long-lived services, a PID file or systemd unit is a more reliable reference than repeated pattern lookups.

Other frequent problems arise from matching rules and visibility. The table below lists typical symptoms with their causes and fixes.

SymptomCauseFix
No match for a long program nameName truncated to 15 charactersUse -f or a shorter pattern
Too many matchesUnanchored substring patternAdd -x or ^...$ anchors
Script finds its own wrapper-f pattern appears in a parent shellNarrow the pattern or filter by parent
Processes of other users missinghidepid mount option on /procRun with appropriate privileges
Container processes listed on hostHost sees all PID namespacesFilter with --ns or --nslist
Typical pgrep problems and fixes
  • Patterns are regular expressions, so characters such as . and + need escaping when a literal match is intended.
  • Output order is not guaranteed to be meaningful; use -n or -o when the newest or oldest process matters.
  • Zombie processes still appear in /proc and can be matched, even though they no longer run code.

Explained without jargon

Every program running on a Linux computer gets an identification number, much like a ticket number at a service counter. When you want to do something with a program, such as check that it is running or stop it, you first need that number.

pgrep is a search tool for those numbers. You give it a name, or a few clues such as who started the program, and it tells you the numbers of every program that fits. It only looks and reports; it never changes anything. That is why administrators use it as a careful first step before taking any action on a running program.

A typical use case

A system administrator runs a reporting job on a Linux server every night at 02:00 through cron. The job is a Python script, nightly_report.py, that usually takes about 40 minutes. On some nights, a slow database makes the job run past the next scheduled start, and two copies begin to compete for the same tables.

The administrator adds a guard at the top of the cron wrapper: if pgrep -u reports -f 'python3 .*nightly_report.py' >/dev/null; then exit 0; fi. The `-f` option is required because the process name is simply python3, and the -u reports filter ensures that a developer testing the script under a personal account does not block the production run.

After the change, overlapping runs disappear. The guard costs a few milliseconds per start and removes duplicate jobs entirely, and the same pgrep command, with -a added, becomes the administrator’s quick check for whether the report is still running.