pgrep - Linux


Overview

pgrep is a command-line utility in Linux that searches for processes running on the system based on given criteria and outputs the process IDs. It is primarily used to locate processes by name or other attributes without needing to parse the full output of ps. pgrep is highly effective in scripting and process management to check if a specific process is running, and to manipulate process IDs directly.

Syntax

The basic syntax of the pgrep command is:

pgrep [options] pattern
  • pattern: Specifies the target pattern to search for among the process names.

Usage

pgrep [options] [--] pattern
pgrep [options]
  • -- signifies the end of options and the beginning of the pattern.

Options/Flags

  • -d <delim>: Specify a delimiter to be used between each process ID in the output. The default is the newline character.
  • -l: Include the process name in the output, next to each PID.
  • -a: Include command line in the output, not just the process ID.
  • -v: Negate the match; return process IDs that do not match the pattern.
  • -u <uids>: Match processes whose effective user ID is given. IDs must be numeric and comma-separated.
  • -n: Returns only the PID of the newest (most recently started) process.
  • -o: Returns only the PID of the oldest process.
  • -P <ppid>: Match only processes with the specified parent process ID.
  • -g <pgrp>: Match processes in the given process group.
  • -s <sid>: Match processes in the given session ID.
  • -t <tty>: Match processes running on the given terminals. Use tty names without the /dev/ prefix.

Examples

  1. Find PID by Name:
    Find the PID of the nginx process.

    pgrep nginx
    
  2. Multiple Instances:
    Find PIDs of all instances of ssh and scp.

    pgrep -d, 'ssh|scp'
    
  3. Exclude Certain Users:
    Find all processes that are not owned by user ID 1001.

    pgrep -v -u 1001
    
  4. Find by Session and Terminal:
    List processes belonging to session ID 1234 and terminal tty1.

    pgrep -s 1234 -t tty1
    

Common Issues

  • Misidentification: pgrep might misidentify processes if partial names match. Use specific patterns or check full command lines with -a to avoid this.
  • Permission Errors: Trying to examine processes owned by other users without proper permissions may lead to errors. Run as root or with sufficient privileges.

Integration

Combine pgrep with kill to terminate processes by name:

kill $(pgrep nginx)

Use with xargs for bulk process handling:

pgrep apache2 | xargs kill -9
  • pkill: Similar to pgrep, but allows direct sending of signals to processes found.
  • pstree: Display running processes in a tree format, which can be useful for understanding process hierarchies.
  • ps: Provides detailed information about currently running processes.

For more information, visit the manual pages with man pgrep.