pgrep / pkill
Overview
pgrep lists PIDs matching selection criteria; pkill sends signals to those processes. Both understand process names, users, and full command lines better than brittle ps | grep pipelines.
Syntax
pgrep [options] pattern
pkill [options] patternCommon Options
| Option | Description |
|---|---|
-a |
Show full command line (pgrep) |
-l |
List name and PID |
-u user |
Only this user |
-f |
Match full command line |
-x |
Exact name match |
-n / -o |
Newest / oldest only |
-signal |
Signal name or number (pkill) |
-c |
Count matches |
Key Use Cases
- Find PIDs by name for scripts
- Signal groups of workers
- Avoid
ps | grepfalse positives - Operate on one user’s processes only
Safety
pkill pattern can match more than you expect — prefer -x, -f with a specific string, and -u. On production, prefer systemctl stop/restart for managed units.
Examples with Explanations
Find nginx worker PIDs
pgrep -a nginxNames plus args; good sanity check before signaling.
Exact name
pgrep -x sshdAvoids matching sshd-session style names unless wanted.
Graceful reload pattern
pkill -HUP nginx
# or: kill -HUP $(pgrep -x nginx | head -1)SIGHUP is conventional for config reload when supported.
Kill only your processes
pkill -u "$USER" -f "python train.py"User filter reduces collateral damage on shared hosts.
Count
pgrep -c -u www-data php-fpmUseful in monitoring scripts.
Notes & Pitfalls
- Both tools share selection flags; difference is list vs signal.
- Exit status 0 = match found, 1 = no match.