124

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)

Lewis Norton
  • 5,971
  • 1
  • 17
  • 28
Dennis Ich
  • 3,045
  • 6
  • 23
  • 40

6 Answers6

252

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.

Shawn Chin
  • 74,316
  • 17
  • 152
  • 184
  • 4
    ps is overused, and pgrep so underused. Thanks for the post. – Felipe Alvarez Nov 25 '13 at 04:23
  • 9
    One way to pass the output to kill is: `kill -9 \`pgrep -f keyword\`` – Kris Jan 19 '17 at 10:11
  • This answer is the best ever. **So** much time I've wasted with `ps aux | grep chrome` – Brandon Feb 27 '17 at 14:23
  • 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!) – ArtOfWarfare Jul 10 '18 at 19:17
  • 2
    @Kris for this use case wouldn't be more straightforward to just use `pkill -9 -f keyword`? – oidualc Oct 04 '19 at 07:10
54

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.

Lewis Norton
  • 5,971
  • 1
  • 17
  • 28
25

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

Kris
  • 16,882
  • 6
  • 79
  • 99
Vinayak
  • 251
  • 3
  • 2
8

I use

ps -C "keyword" -o pid=

This command should give you a PID number.

GAntoine
  • 1,097
  • 2
  • 17
  • 26
Arksonic
  • 81
  • 1
  • 1
8

This is available on linux: pidof keyword

dbrank0
  • 8,226
  • 2
  • 33
  • 48
5

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}'`"
swayamraina
  • 2,199
  • 17
  • 20