pgrep Command

The pgrep command in Linux is a command-line utility that searches for processes based on various criteria and prints their process IDs (PIDs) to standard output. It is extremely useful for scripting and automating tasks related to process management, as it provides a more direct and efficient way to find PIDs compared to parsing the output of ps and grep.

Syntax

pgrep [OPTION]... PATTERN

Description

pgrep searches the currently running processes and lists the PIDs of those that match the given criteria. The criteria can be a process name, a user ID, a group ID, or other attributes. It is often used in conjunction with pkill to terminate processes found by pgrep.

Common uses include:

  • Finding the PID of a process by its name.
  • Listing processes owned by a specific user or group.
  • Identifying processes based on their full command line.
  • Integrating with scripts for automated process control.

Common Options

Option Description
-u, --euid <user> Match processes whose effective user ID is <user>.
-G, --egid <group> Match processes whose effective group ID is <group>.
-f, --full The pattern is matched against the full command line.
-l, --list-name List the process name in addition to the PID.
-n, --newest Select the newest (most recently started) of the matching processes.
-o, --oldest Select the oldest (least recently started) of the matching processes.
-x, --exact Only match processes whose name is exactly PATTERN.
-P, --parent <ppid> Match only children of the process with specified parent PID.

Examples

Find PID of a process by name

pgrep sshd
# Example Output: 1234

Returns the Process ID (PID) of the sshd process.

Find PIDs of processes owned by a specific user

pgrep -u root

Lists all PIDs of processes running as the root user.

Find PID by full command line

pgrep -f "python my_script.py"

Finds the PID of a Python script by matching its full command line.

List PID and process name

pgrep -l nginx
# Example Output: # 5678 nginx # 5679 nginx

Displays both the PID and the name of matching processes.

Find the newest process by name

pgrep -n firefox

Returns the PID of the most recently started firefox process.

See also