Linux commands
Browse topics

Selecting and signaling processes by name with pgrep and pkill

Version
unversioned
Review
Draft

Summary#

pgrep prints the IDs of processes that match a pattern. pkill sends a signal to the same selection.

Syntax#

sh
pgrep -l nginx
pgrep -x sshd
pgrep -af 'python3 worker\.py'
pkill -TERM -f 'python3 worker\.py'
pgrep -u "$USER"

The pattern is an extended regular expression matched against the process name. -f matches the whole command line, -x requires an exact match, -a prints the command line and -u restricts the selection to a user. pkill sends TERM unless you name another signal.

Example#

sh
(
  set -eu
  dir=$(mktemp -d)
  worker=
  trap 'if [ -n "$worker" ]; then
      kill "$worker" 2>/dev/null || true
      wait "$worker" 2>/dev/null || true
    fi
    rm -rf -- "$dir"' EXIT

  cat > "$dir/worker.sh" <<'WORKER'
trap 'kill "$child"; exit 0' TERM
sleep 30 &
child=$!
echo ready > "$1"
wait "$child"
WORKER
  sh "$dir/worker.sh" "$dir/ready" &
  worker=$!
  until [ -s "$dir/ready" ]; do sleep 0.1; done

  test "$(pgrep -f "$dir/worker.sh")" = "$worker"
  echo 'pgrep matched the worker'
  pkill -TERM -f "$dir/worker.sh"
  wait "$worker"
  worker=
  pgrep -f "$dir/worker.sh" >/dev/null || echo "no match, status $?"
)

Expected output#

Text
pgrep matched the worker
no match, status 1

Common mistakes#

Run pgrep -af pattern before pkill -f pattern: a short pattern can match editors, shells and unrelated services whose command lines contain it. The process name that pgrep matches without -f is limited to 15 characters. A longer pattern prints a warning that a pattern that searches for process name longer than 15 characters will result in zero matches, so use -f. killall name from psmisc matches names rather than a regular expression, and killall on some other Unix systems signals every process.

Version applicability#

This entry describes pgrep and pkill from procps-ng 4. BSD and macOS versions support a different set of options.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0