pgrep multiple process names
Asked Answered
G

1

6

I want to get PIDs of two or more processes using "pgrep" command in Linux.

As we know pgrep syntax is

pgrep [options] <pattern>

Here is a hypothetical command which should return PIDs of two processes whose names are process1 and process2 respectively.

pgrep process1 OR process2 

What should be the pattern that needs to be used to achieve the above?

Gastongastralgia answered 23/10, 2019 at 16:53 Comment(3)
what are the real process names you need to grep?Few
The real process names are nginx and javaGastongastralgia
From man pgrep: pgrep [options] pattern and pattern: Specifies an Extended Regular Expression for matching against the process names or command lines.Countercheck
D
7

Try:

pgrep 'process1|process2'

Example:

 -->pgrep 'atd|cron'
1078
1093

 -->ps -eaf |grep -E 'atd|cron'
daemon    1078     1  0 Aug08 ?        00:00:00 /usr/sbin/atd -f
root      1093     1  0 Aug08 ?        00:00:19 /usr/sbin/cron -f
xxxx  14364  9597  0 11:56 pts/2    00:00:00 grep -E atd|cron
Dissimulation answered 23/10, 2019 at 16:57 Comment(3)
Be careful, as this is totally wrong. Pgrep uses regexp matching, so atd|cron can match not only atd & cron but for instance rpc.statd or crond.Marchetti
Its not wrong. Idea for this answer is to tell OP how to use Or condition. When pipe is used for OR condition, it was implied that regex is used. Yes, they need to use word boundaries to prevent false positive.Dissimulation
You can just use exact match like this pgrep -x 'atd|cron', or pgrep '^(atd|cron)$'.Liv

© 2022 - 2024 — McMap. All rights reserved.