Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting pids from ps -ef |grep keyword

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)

like image 736
Dennis Ich Avatar asked Oct 14 '22 00:10

Dennis Ich


People also ask

How do you grep a PID of a process?

A PID is automatically assigned to each process when it is created. A process is nothing but running instance of a program and each process has a unique PID on a Unix-like system. The easiest way to find out if process is running is run ps aux command and grep process name.

What is ps grep for?

I use ps command to find out all running process on my Linux and Unix system. The ps command shows information about a selection of the active processes on the shell. You may also pipe out ps command output through grep command to pick up desired output.


2 Answers

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.

like image 277
Shawn Chin Avatar answered Oct 21 '22 16:10

Shawn Chin


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.

like image 62
Lewis Norton Avatar answered Oct 21 '22 16:10

Lewis Norton