kmail.at
contact

elsewhere

EnglishEN
← learning

sysadmin · difficulty ◆◆

pgrep — find processes by name, then signal them

ps | grep is a pipeline with two bugs. pgrep is the fix.

The command you use to kill a process is one character away from killing your own ssh session — and this one will not warn you.

fully AI-generatedThis text is fully AI-generated and was published without human editorial review.

2026-10-18 · 5 min read

$ pgrep

One binary instead of a four-stage pipeline

The classic idiom is `ps -ef | grep orders_worker | grep -v grep | awk '{print $2}'`, and it has a bug everyone meets on day one: the grep process contains the search string in its own command line, so it matches itself. Hence `grep -v grep`, which then throws away any legitimate process that happens to have the word grep in its arguments. Two filters cancelling each other out.

pgrep is that pipeline distilled. It scans the process table, matches a pattern against each process name, prints the PIDs (or the full command line with `-a`), and sets an exit status: 0 if something matched, 1 if nothing did, 2 for a bad command line, 3 for a fatal error. The man page is explicit that the running pgrep never reports itself as a match, which is the whole point.

pkill is the same matcher with a signal at the end. Its default is SIGTERM. Because both use identical pattern semantics, `pgrep -f 'pattern'` is a free dry run: look at what it printed, then repeat the command with a p in front.

The name is 15 characters, and that is a kernel limit

Without `-f`, pgrep matches the process name from `/proc/<pid>/stat`, and the kernel stores that in a 16-byte field. Fifteen characters plus the terminator. So a process called `orders_worker_production.py` is only visible to pgrep as `orders_worker_p`, and a pattern for the full name silently matches nothing. pgrep at least tells you:

`pgrep: pattern that searches for process name longer than 15 characters will result in zero matches`

That is the same reason every Python job shows up as `python3`, every Node job as `node`, and every Java job as `java`. With interpreters, the process name tells you nothing at all, and you must use `-f` to match the command line instead. My rule: `-f` for anything launched through an interpreter, plain name matching for native daemons like sshd, chronyd or nginx.

Careful with the direction of that: `-f` matches the whole command line, so anything that merely mentions the pattern matches too — your editor, a shell script, the monitoring agent's wrapper, and the parent shell you typed the command into.

TERM, wait, KILL — in that order

SIGTERM asks the process to shut down: it flushes buffers, closes sockets, releases locks. SIGKILL cannot be caught and leaves whatever it was holding in place. So the sequence is pkill -TERM, wait for pgrep to start returning exit code 1, then escalate only if it is still there. A loop does it honestly:

`pkill -TERM -f 'orders_worker.py'; while pgrep -f 'orders_worker.py' >/dev/null; do sleep 1; done; pgrep -f 'orders_worker.py' >/dev/null && pkill -KILL -f 'orders_worker.py'`

pkill's own exit status is about whether a signal reached anyone: 0 if at least one process was signalled, 1 if none matched or none could be signalled. A 1 from a kill command usually means the process already died on its own, which is good news, not an error to page someone about.

Daemons that reload without restarting are worth knowing: `pkill -HUP -f gunicorn` makes the master fork new workers, `pkill -HUP nginx` is how you get a config change live without dropping a single connection.

Example

$ pgrep -a -f orders_worker
1974782 python3 jobs/orders_worker.py --tenant 41
1974783 python3 jobs/orders_worker.py --tenant 42

-f matches the whole command line (needed, since the process name is just python3) and -a prints that command line next to the PID. Without -a you get two bare numbers and no way to tell them apart.

$ pgrep -n -f 'python3 jobs'
1974784

-n returns only the newest match, -o the oldest. After a restart this is the process you want to watch; during a leak investigation it is -o, because the oldest PID is the one that has been eating memory longest.

$ pgrep -c -f orders_worker; pgrep -c -f report_builder
2
1

-c counts matching processes — the equivalent of `ps | grep | wc -l` without the self-match problem. Exit status is still 1 when the count is zero, so it works in `if` too.

$ pkill -TERM -f 'orders_worker.py --tenant 42'; echo "pkill exit=$?"
pkill exit=0

TERM is the default signal, but I write it anyway so the next person reading the script knows this is a graceful stop and not a hard kill.

$ sleep 0.4; pgrep -f 'orders_worker.py --tenant 42'; echo "pgrep exit=$?"
pgrep exit=1

Exit 1 with no output means the process is gone — that is the success condition after a kill, and the condition to test in a wait loop. Reading exit 1 as an error is the most common scripting mistake with pgrep.

$ pgrep thisisaverylongprocessname
pgrep: pattern that searches for process name longer than 15 characters will result in zero matches
Try `pgrep -f' option to match against the complete command line.

That warning is not a suggestion. The name field is 15 characters wide, so this pattern can never match anything on the system. Add -f and match the command line instead.

Common flags

-f
Match the full command line instead of the 15-character process name. Required for anything started via python3, node, java or bash -c.
-a
List the full command line after each PID — the flag that makes the output usable without a second ps call.
-n / -o
Newest or oldest matching process only. Fast way to find the just-restarted worker or the longest-running leak.
-c
Print a count of matching processes instead of PIDs; exit status still reflects whether any matched.
-x
Require the whole name to match exactly, so `pgrep -x ssh` does not match sshd and ssh-agent.
-u
Only match processes owned by the given user (effective UID); -U uses the real UID, which matters for setuid daemons.
-P
Only match children of the given PID — how you find the worker that a supervisor actually owns.

History

Born on Solaris because ps | grep was embarrassing

pgrep and pkill first shipped in Solaris 7 in 1998, at a time when every SysV admin had the `ps -ef | grep name | grep -v grep | awk '{print $2}'` incantation in their notes. The whole design is that pipeline turned into a C program: scan /proc, match, print PIDs, optionally signal. Linux picked the pair up through the procps package, and there they are today — same two binaries, same flags, on every distribution including the minimal containers where ps itself is missing.

procps-ng 4.0 added a third sibling, `pidwait`, which blocks until the matching processes exit instead of printing their PIDs. If your box has it, the wait loop in the section above becomes `pidwait -f orders_worker.py`.

Why the pattern is a regex, and why that bites

pgrep does not do substring matching or globbing. It compiles your pattern as an extended regular expression and matches it, unanchored, against the name or the command line. That is convenient — `pgrep -f 'worker\.py --tenant 4[12]'` works — and dangerous, because an unanchored regex is a very broad net. `pkill -f 8080` matches the python server on port 8080, your notes file open in vim, the ssh session whose command line mentions the port, and the shell that launched them all.

The safe form anchors both ends and includes the interpreter: `pkill -f '^python3 jobs/orders_worker.py --tenant 42$'`. Ugly, but it can only match the one process you meant. The man page's other useful promise is that pgrep, pkill and pidwait never report themselves as a match — the self-kill risk is the parent shell, not the tool.

Fun facts

Pros & cons

pros

  • + Kills the ps|grep self-match problem in one command, and its exit status (0/1/2/3) is precise enough to script against.
  • + One pattern language for finding and signalling, so `pgrep -af` is a genuine dry run for the pkill you are about to run.
  • + Fast on a box with thousands of processes — it reads /proc directly instead of formatting a table.

cons

  • − Unanchored regex plus -f is a wide net; the difference between the right process and a dozen bystanders is two carets.
  • − The 15-character name limit makes plain name matching useless for anything launched through an interpreter, which is most modern services.
  • − It tells you nothing about resource use or start time; you still go back to ps or top for CPU, memory and elapsed time.

Takeaways

  1. 1Replace `ps aux | grep name | grep -v grep` with `pgrep -af name` — one process, no self-match, full command lines attached.
  2. 2Use -f for anything started by an interpreter, and anchor it: '^python3 jobs/orders_worker.py' matches your worker, 'worker' matches half the box.
  3. 3Treat pgrep exit 1 as 'nothing found', not as an error — it is the success condition of every wait-for-exit loop.
  4. 4TERM, wait, then KILL. `pkill -KILL` on a database or a process holding a lock costs more than the seconds you saved.
  5. 5Dry-run every pkill with the same flags on pgrep first, and prefer `pkill -HUP` for daemons that can reload their config in place.

Related commands

archive entry — written and published by a scheduled job, never editorially reviewed. Kept for reference: out of the site’s search index, and no ads run here. the reviewed library →

← all learning