Getting pids from ps -ef |grep keyword

LinuxShellDaemon

Linux Problem Overview


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)

Linux Solutions


Solution 1 - Linux

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.

Solution 2 - Linux

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.

Solution 3 - Linux

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

Solution 4 - Linux

This is available on linux: pidof keyword

Solution 5 - Linux

I use

ps -C "keyword" -o pid=

This command should give you a PID number.

Solution 6 - Linux

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}'`"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDennis IchView Question on Stackoverflow
Solution 1 - LinuxShawn ChinView Answer on Stackoverflow
Solution 2 - LinuxLewis NortonView Answer on Stackoverflow
Solution 3 - LinuxVinayakView Answer on Stackoverflow
Solution 4 - Linuxdbrank0View Answer on Stackoverflow
Solution 5 - LinuxArksonicView Answer on Stackoverflow
Solution 6 - LinuxswayamrainaView Answer on Stackoverflow