How to get the pid of a running process using a single command that parse the output of ps?

22

3

I am looking for a single line that does return the pid of a running process.

Currently I have:

ps -A -o pid,cmd|grep xxx|head -n 1

And this returns the fist pid, command. I need only the first number from the output and ignore the rest. I suppose sed or awk would help here but my experience with them is limited.

Also, this has another problem, it will return the pid of grep if the xxx is not running.

It's really important to have a single line, as I want to reuse the output for doing something else, like killing that process.

sorin

Posted 2012-05-23T17:25:38.130

Reputation: 9 439

1pipe it through head and specify the line to return with -n 1? – Mike McMahon – 2012-05-23T17:31:12.137

Answers

28

If you just want the pid of the process you can make use of pgrep if available. pgrep <command> will return the pid of the command (or list of pids in case there are more than one instance of the command running, in which case you can make use of head or other appropriate commands)
Hope this helps!

another.anon.coward

Posted 2012-05-23T17:25:38.130

Reputation: 401

+1 My usual use of pgrep: kill \pgrep xxx`` – Steve – 2012-05-23T22:34:34.227

20@steve: Perhaps you should look at pkill. – Paused until further notice. – 2012-05-24T01:17:14.073

7

Just one more command needed; you want only the first field from a line of space-separated values:

ps -A -o pid,cmd|grep xxx | grep -v grep |head -n 1 | awk '{print $1}'

Well, two. I added another grep to remove grep itself from the output.

chepner

Posted 2012-05-23T17:25:38.130

Reputation: 5 645

6

Just use pgrep, it's much more straight forward

pgrep -o -x xxxx

The above selects the oldest process with the exact name

Lenny

Posted 2012-05-23T17:25:38.130

Reputation:

And since OP wants to use the command to kill the process, pkill (with the same args) would be the most direct choice. – bstpierre – 2012-09-30T01:59:03.817

3

pidof xxx will suffice on linux

herve3527

Posted 2012-05-23T17:25:38.130

Reputation: 31

0

Running on Cygwin so I can't use -A and -o, but something like this:

$ ps
      PID    PPID    PGID     WINPID   TTY     UID    STIME COMMAND
     4580       1    4580       4580  ?       55573   May 21 /usr/bin/mintty
     5808    7072    5808       7644  pty3    55573 13:35:31 /usr/bin/ps
     7072    5832    7072       6424  pty3    55573   May 21 /usr/bin/bash


$ ps | grep '/usr/bin/mintty' | head -n 1 | awk '{print $1}'
4580

AlG

Posted 2012-05-23T17:25:38.130

Reputation: 315

0

you can do something like

ps -A -o cmd,pid | egrep "^xxx " | head -n 1 | sed -r -e 's/.* ([0-9]+)$/\1/'

then xxx has to be process name and it will not pick up grep because of the anchor ^

pizza

Posted 2012-05-23T17:25:38.130

Reputation: 101