1

I'm trying to get the PID's of a certain service. I'm trying to do that with the following command:

ps aux | grep 'DynamoDBLocal' | awk '{print $2}'

Gives output:

1021
1022
1161

This returns me 3 PID's, 2 of the service that I want, and 1 for the grep it just did. I would like to remove the last PID (the one from the grep) out of the list.

How can I achieve this?

ThomasVdBerge
  • 7,483
  • 4
  • 44
  • 62
  • 1
    There is a nice approach to this topic in http://stackoverflow.com/a/3510850/1983854 . It is the same, but over there they also call the `kill` to kill the process. – fedorqui Nov 01 '13 at 09:22
  • 1
    Note that `grep re | awk '{print field}` can be replaced by `awk '/re/ {print field}'`. – Thor Nov 01 '13 at 09:32

7 Answers7

8

Just use pgrep, it is the correct tool in this case:

pgrep 'DynamoDBLocal'
perreal
  • 94,503
  • 21
  • 155
  • 181
3

Using grep -v:

ps aux | grep 'DynamoDBLocal' | grep -v grep | awk '{print $2}'

If you have pgrep in your system

pgrep DynamoDBLocal
falsetru
  • 357,413
  • 63
  • 732
  • 636
3

You can say:

ps aux | grep '[D]ynamoDBLocal' | awk '{print $2}'
devnull
  • 118,548
  • 33
  • 236
  • 227
3

With a single call to awk

ps aux | awk '!/awk/ && /DynamoDBLocal/{print $2}'
Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
3

Try pidof, it should give you the pid directly.

pidof DynamoDBLocal
Jotne
  • 40,548
  • 12
  • 51
  • 55
2

Answering the original question: How to remove lines from output:

ps aux | grep 'DynamoDBLocal' | awk '{print $2}' | head --lines=-1

head allows you to view the X (default 10) first lines of whatever comes in. Given a value X with minus prepended it shows all but the last X lines. The 'inverse' is tail, btw (when you are interested in the last X lines).

However, given your specific problem of looking for PIDs, I recommend pgrep (perreals answer).

Felix
  • 4,510
  • 2
  • 31
  • 46
1

I'm not sure that ps aux | grep '...' is the right way.

But assuming that it is right way, you could do

ps aux | grep '...' | awk '{ if (prev) print prev; prev=$2 }'
cinsk
  • 1,576
  • 2
  • 12
  • 14