Website Vidya
Linux & ServersStep-by-Step Guide

pkill Command in Linux: Stop Processes by Name, User, and Pattern

Learn pkill command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

RR
Rajesh RayLead Systems Educator
Published:
10 min read
PDF Cheat Sheet
pkill Command in Linux: Stop Processes by Name, User, and Pattern
AI Executive SummaryWebsiteVidya AI

10 min read

Learn pkill command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What pkill Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

The pkill command in linux eliminates the tedious two-step workflow of searching for Process IDs with ps and copying numbers into kill. Packaged inside procps-ng and built from the exact same source code as pgrep, pkill evaluates extended regular expressions and process metadata filters to signal matching processes in a single atomic operation.

By default, running pkill pattern performs a partial substring match against the short process name (stored in /proc/PID/comm, which the Linux kernel truncates to 15 characters) and delivers SIGTERM (signal 15) to every matching process. Because substring matching is the default, running pkill ssh could match both ssh and sshd unless you constrain the match with -x (exact match) or test the filter first using pgrep -a.

What sets pkill apart from kill and killall is its rich attribute filtering: you can target only the newest (-n) or oldest (-o) matching process, restrict signals to processes owned by a specific effective user ID (-u), target children of a parent PID (-P), or clear every process attached to a hung SSH pseudo-terminal (-t pts/2).

Advertisement
pkill Command in Linux: Stop Processes by Name, User, and Pattern — syntax, flags, and practical terminal workflow diagram
pkill Command in Linux: Stop Processes by Name, User, and Pattern — command syntax, key options, and production workflow reference.

What pkill Does and When to Use It

In the procps-ng source tree, pgrep and pkill share the same underlying binary logic and /proc scanner. When invoked as pkill, the utility iterates over /proc/[0-9]*, skips its own PID and ancestors if appropriate, applies POSIX Extended Regular Expression (ERE) compilation via regcomp(3) along with any UID, GID, PPID, PGRP, or TTY predicates, and invokes kill(2) (or sigqueue(3)) on each matched task.

Crucially, unless you pass the -f (--full) option, pkill only compares your pattern against the 15-byte comm field in /proc/PID/stat. If a process has a binary name longer than 15 characters or runs inside an interpreter like python3 /opt/workers/invoice_generator.py, standard pkill invoice_generator will not match because comm is simply python3; passing pkill -f invoice_generator.py instructs pkill to inspect the full /proc/PID/cmdline buffer instead.

Under the hood, pkill 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 -f, -x, -u, -P turns raw process and service tables into actionable diagnostics during incident response.

Availability and Installation Across Linux Distributions

The pkill 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:

Advertisement

Before running administrative tasks or automation scripts, verify whether pkill is installed and inspect which binary path and version your shell resolves:

type -a pkill
pkill --version 2>/dev/null || man -f pkill

# Illustrative output (reviewed against documentation)
pkill is /usr/bin/pkill
pkill (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

pkill [OPTIONS] [-SIGNAL] [PATTERN]

The general syntax is pkill [-SIGNAL | --signal SIGNAL] [OPTIONS] [PATTERN]. Signals may be specified either as a leading option such as pkill -9 pattern, pkill -HUP pattern, or explicitly via pkill --signal SIGTERM pattern. If you filter by user (-u), terminal (-t), or parent PID (-P), providing a PATTERN argument becomes optional.

When combining multiple filter flags (for example, pkill -u www-data -f worker.php), pkill applies logical AND semantics between different filter types, meaning a process is signaled only if it belongs to www-data and its command line matches worker.php. Within a single comma-separated flag (such as -u alice,bob), logical OR semantics apply.

  • 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 / FlagLong Form / ArgumentTechnical Behavior and Purpose
-f--fullMatches the regular expression pattern against the entire command line (/proc/PID/cmdline) rather than only the 15-character process name.
-x--exactRequires the pattern to match the entire process name (or entire command line if combined with -f) rather than a partial substring.
-u--euid EUID,...Only signals processes whose effective user ID or username matches the comma-separated list.
-P--parent PPID,...Only signals child processes whose immediate Parent Process ID (PPID) matches the given value.
-t--terminal TERM,...Only signals processes attached to the specified controlling terminal (e.g., pts/1 or tty2).
-n--newestSelects and signals only the single most recently started (newest) process among all matches.
-o--oldestSelects and signals only the single earliest started (oldest) process among all matches.
-e--echoDisplays the name and PID of each process as it is killed (verbose confirmation mode).
-i--ignore-casePerforms case-insensitive regular expression matching against process names or command lines.

Because pkill uses substring regular expressions by default, adding -e (--echo) and -x (--exact) is a best practice for interactive terminal administration. Running pkill -e -x redis-cli guarantees you will not accidentally kill redis-server and prints an explicit confirmation line for every terminated PID.

Advertisement

Whenever you plan to use pkill -f with a pattern, always dry-run the exact same arguments with pgrep -fa <pattern> first. Because pgrep and pkill share identical matching rules, whatever pgrep -fa prints is guaranteed to be the exact set of processes pkill -f will signal.

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. Gracefully Stop Processes by Exact Name with Confirmation (-e -x)

Use -x to enforce an exact binary name match and -e to echo the PID and name of each terminated process.

pkill -e -x redis-benchmark

# Illustrative output (reviewed against documentation)
redis-benchmark killed (pid 22410)
redis-benchmark killed (pid 22411)

The -x flag prevents partial substring matches (ensuring redis-server is untouched), while -e prints confirmation for each PID that received SIGTERM.

2. Kill a Background Script by Matching Its Full Command Line (-f)

Preview matching processes with pgrep -fa first, then use pkill -f to stop a specific Python or Node.js worker script.

pgrep -fa "queue=high_priority"
pkill -e -f "python3 /opt/app/worker.py --queue=high_priority"

# Illustrative output (reviewed against documentation)
24102 python3 /opt/app/worker.py --queue=high_priority
worker.py killed (pid 24102)

Without -f, pkill only checks the binary name (python3). Passing -f inspects the full command-line argument string so you can target one specific worker queue while leaving other python3 processes running.

3. Terminate Only the Newest or Oldest Matching Process (-n / -o)

If a newly spawned browser tab or worker process is hung, pass -n (--newest) to terminate only the most recently created instance.

pkill -e -n chrome

# Illustrative output (reviewed against documentation)
chrome killed (pid 28914)

The -n option compares start timestamps in /proc/PID/stat and signals only the newest process, leaving older parent processes intact.

4. Stop All Processes Owned by a Specific User Account (-u)

Terminate all active processes (or specific processes) belonging to a compromised or departing user account with sudo pkill -u.

# Kill only 'python3' processes owned by user 'sandbox':
sudo pkill -e -u sandbox python3

# Or terminate every process owned by 'sandbox':
sudo pkill -TERM -u sandbox

# Illustrative output (reviewed against documentation)
python3 killed (pid 29104)
python3 killed (pid 29108)

Combining -u <username> with a process name applies an AND filter; omitting the process name targets all processes running under that effective UID.

5. Kill All Child Processes of a Specific Parent PID (-P)

Clean up runaway child worker processes spawned by a master daemon or shell script without killing the parent process itself.

pkill -e -TERM -P 1104

# Illustrative output (reviewed against documentation)
nginx killed (pid 29410)
nginx killed (pid 29411)

Passing -P 1104 signals only direct child processes whose PPID is 1104, leaving PID 1104 untouched.

6. Close a Frozen SSH Session by Terminal Device (-t)

If one of your SSH terminal tabs freezes due to a broken network pipe, identify its pseudo-terminal with w and terminate processes on that PTY.

w
sudo pkill -e -HUP -t pts/2

# Illustrative output (reviewed against documentation)
19:40:11 up 42 days,  6:34,  2 users,  load average: 0.12, 0.20, 0.18
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
admin    pts/0    198.51.100.12    18:40    0.00s  0.04s  0.00s w
admin    pts/2    198.51.100.12    14:10    5:20m  0.12s  0.12s vim /etc/hosts
vim killed (pid 11204)
bash killed (pid 11180)

Sending SIGHUP (-HUP) to -t pts/2 cleanly disconnects the hung terminal session without affecting your active pts/0 session.

Real-World Workflows, Pipelines, and Shell Automation

Safe Dry-Run Preview and Scoped Termination Pipeline

Write a wrapper script that previews every process matched by pgrep -fa before executing pkill -f, preventing accidental broad matches.

#!/usr/bin/env bash
set -euo pipefail

PATTERN="${1:?Usage: $0 <regex-pattern>}"

echo "=== Dry-Run: Processes matching pattern '$PATTERN' ==="
if ! pgrep -fa "$PATTERN"; then
  echo "No matching processes found."
  exit 0
fi

echo "=== Sending SIGTERM via pkill -e -f ==="
pkill -e -TERM -f "$PATTERN"

# Illustrative output (reviewed against documentation)
=== Dry-Run: Processes matching pattern 'celery.*--queues=reports' ===
30412 /opt/venv/bin/python3 /opt/venv/bin/celery -A app worker --queues=reports
30413 /opt/venv/bin/python3 /opt/venv/bin/celery -A app worker --queues=reports
=== Sending SIGTERM via pkill -e -f ===
celery killed (pid 30412)
celery killed (pid 30413)

Pairing pgrep -fa with pkill -e -f creates an auditable log trail in CI/CD deployment output showing the exact command lines that were terminated.

Zero-Downtime Worker Recycling Using SIGUSR2 or SIGHUP

Many application servers (Gunicorn, Unicorn, Nginx, Puma) use SIGUSR2 or SIGHUP to recycle workers or reopen rotated log files. Use pkill -f to dispatch custom signals cleanly.

# Signal Gunicorn master process to gracefully restart workers after code deploy
pkill -e -HUP -f "gunicorn: master [billing_api]"
pgrep -fa "gunicorn:.*billing_api"

# Illustrative output (reviewed against documentation)
gunicorn killed (pid 19500)
19500 gunicorn: master [billing_api]
31901 gunicorn: worker [billing_api]
31902 gunicorn: worker [billing_api]

Notice that 'gunicorn killed (pid 19500)' in pkill -e output simply means the signal (SIGHUP) was delivered to PID 19500; the master process stays alive and spawns fresh workers (31901, 31902).

Pipelines, Redirection, Quoting, and Shell Expansion

When embedding pkill 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

Like kill, an unprivileged invocation of pkill can only deliver signals to processes owned by the caller's effective UID. If a pattern matches both your own processes and another user's processes, pkill signals yours and reports Operation not permitted for the others unless you filter by your own UID with pkill -u "$(id -u)".

When running sudo pkill as root, always combine -u <service_user> or -x so a broad regular expression cannot accidentally match root system daemons.

GNU/Linux, BSD, and BusyBox Implementation Differences

pkill originated in Solaris 7 and is available across Linux (procps-ng), FreeBSD, OpenBSD, NetBSD, macOS, and Alpine BusyBox.

However, the -e (--echo) flag is a GNU/Linux procps-ng extension; on macOS and FreeBSD, -e is not supported (use pkill -l or check with pgrep instead).

Troubleshooting Common Errors and Diagnostics

pkill <name> returns exit code 1 (no process found) for a process with a long name

Root Cause: Without -f, pkill matches against /proc/PID/comm, which the Linux kernel truncates to 15 characters.

Resolution: Add the -f flag so pkill matches against the full /proc/PID/cmdline string, or match the first 15 characters of the binary name.

pgrep -fa "my_long_application_name"
pkill -f "my_long_application_name"

A bash script named stop_app.sh kills itself when running pkill -f app

Root Cause: Because the script's own command line is '/bin/bash ./stop_app.sh', it contains the substring 'app' and matches pkill -f app.

Resolution: Make the regular expression more specific or use a character class trick like '[a]pp_daemon' or match the exact binary path.

pkill -f "/usr/local/bin/app_daemon"

pkill: killing pid 1234 failed: Operation not permitted

Root Cause: The pattern matched a process belonging to root or another user account while running without sudo.

Resolution: Scope pkill to your own user account with -u $USER, or prepend sudo if you intend to stop a system process.

pkill -u "$USER" -f "my_worker"

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
By default, pkill treats its argument as a partial Extended Regular Expression (ERE) and supports filtering by user (-u), parent PID (-P), newest (-n), and oldest (-o). killall requires an exact match on the process name by default.
Replace pkill with pgrep -a using the exact same flags and pattern (for example, pgrep -fa 'my_pattern'). Because pgrep and pkill share the same matching engine, pgrep -a lists the exact PIDs and command lines that pkill will signal.
Pass -9 or -KILL before the pattern: pkill -9 -x process_name.
In procps-ng, the -e (--echo) message says '<name> killed (pid <N>)' whenever the kill(2) system call succeeds in delivering any signal, even if the signal was SIGHUP or SIGUSR1 rather than a terminating signal.
RR
Written byVerified Author

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.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout