Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to extract the PID of a process by command line

Tags:

bash

shell

I want to get the PID of a process namely "cron" by command line. I tried the following script.

ps ax|grep 'cron'

but I am getting a part of a table,

   1427 ?        Ss     0:00 /usr/sbin/cron -f
24160 pts/5    S+     0:00 grep --color=auto cron

How I extract the pid from this ?

like image 970
Nitheesh MN Avatar asked Jul 28 '16 11:07

Nitheesh MN


3 Answers

The pgrep utility will return the process IDs for the currently running processes matching its argument:

$ pgrep cron
228

It may also be used to "grep for" things on the command line:

$ pgrep -f uerfale
69749
69752

$ pgrep -l -f uerfale
69749 slogin uerfale
69752 slogin: /home/kk/.ssh/sockets/uerfale-9022-kk.sock [mux] m

To kill a process by name, use pkill. It works in the same way as pgrep but will send a signal to the matched processes instead of outputting a process ID.

like image 179
Kusalananda Avatar answered Oct 17 '22 21:10

Kusalananda


Just use pidof, rather to use other commands and apply post-processing actions on them.

$ pidof cron
22434

To make the command return only one PID pertaining to to the process, use the -s flag

-s Single shot - this instructs the program to only return one pid.

like image 35
Inian Avatar answered Oct 17 '22 21:10

Inian


Like this, for example:

ps -ef|grep 'cron'|grep -v grep|awk '{print $2}'
like image 2
AwkMan Avatar answered Oct 17 '22 22:10

AwkMan