Getting pids from ps -ef |grep keyword
Asked Answered
C

6

152

I want to use ps -ef | grep "keyword" to determine the pid of a daemon process (there is a unique string in output of ps -ef in it).

I can kill the process with pkill keyword is there any command that returns the pid instead of killing it? (pidof or pgrep doesnt work)

Carden answered 14/11, 2011 at 10:34 Comment(0)
M
295

You can use pgrep as long as you include the -f options. That makes pgrep match keywords in the whole command (including arguments) instead of just the process name.

pgrep -f keyword

From the man page:

-f       The pattern is normally only matched against the process name. When -f is set, the full command line is used.


If you really want to avoid pgrep, try:

ps -ef | awk '/[k]eyword/{print $2}'

Note the [] around the first letter of the keyword. That's a useful trick to avoid matching the awk command itself.

Microorganism answered 14/11, 2011 at 10:41 Comment(5)
ps is overused, and pgrep so underused. Thanks for the post.Gorizia
One way to pass the output to kill is: kill -9 `pgrep -f keyword`Presbyterate
This answer is the best ever. So much time I've wasted with ps aux | grep chromeWeeden
Had to use the [k] trick on pgrep -f. My script was running in a subshell so I think it was picking up its parent command (hard to know for sure - the pid it returned was gone when the command was done executing!)Nee
@Presbyterate for this use case wouldn't be more straightforward to just use pkill -9 -f keyword?Aceto
B
70

Try

ps -ef | grep "KEYWORD" | awk '{print $2}'

That command should give you the PID of the processes with KEYWORD in them. In this instance, awk is returning what is in the 2nd column from the output.

Bowens answered 14/11, 2011 at 10:37 Comment(2)
Because this can return more than one pid you can get the first by appending | head -1.Presbyterate
'head -1' will return grep PID in some linux, Should be tail -1.Sudorific
B
28

ps -ef | grep KEYWORD | grep -v grep | awk '{print $2}'

Buck answered 3/2, 2013 at 4:35 Comment(3)
Perhaps a typo? ps -ef | grep KEYWORD | grep -v grep | awk '{print $2}'Valentinvalentina
Do you know how to pass the returned PID into "kill -9" ?!Onepiece
@Onepiece just add | xargs kill -9 to the endCatheterize
C
12

This is available on linux: pidof keyword

Caton answered 14/11, 2011 at 10:44 Comment(0)
R
11

I use

ps -C "keyword" -o pid=

This command should give you a PID number.

Rodriques answered 14/3, 2016 at 17:50 Comment(0)
G
10

To kill a process by a specific keyword you could create an alias in ~/.bashrc (linux) or ~/.bash_profile (mac).

alias killps="kill -9 `ps -ef | grep '[k]eyword' | awk '{print $2}'`"
Genovera answered 26/2, 2019 at 14:44 Comment(1)
Perfect! Adding a pipe to the end of | head -1 wraps this all up nice and neat.Simplify

© 2022 - 2024 — McMap. All rights reserved.