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
  • 6,316
  • 3
  • 39
  • 58
  • 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

7

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

pgrep 'DynamoDBLocal'
perreal
  • 90,214
  • 20
  • 145
  • 172
3

Using grep -v:

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

If you have pgrep in your system

pgrep DynamoDBLocal
falsetru
  • 336,967
  • 57
  • 673
  • 597
3

You can say:

ps aux | grep '[D]ynamoDBLocal' | awk '{print $2}'
devnull
  • 111,086
  • 29
  • 224
  • 214
3

With a single call to awk

ps aux | awk '!/awk/ && /DynamoDBLocal/{print $2}'
Chris Seymour
  • 79,902
  • 29
  • 153
  • 193
3

Try pidof, it should give you the pid directly.

pidof DynamoDBLocal
Jotne
  • 39,326
  • 11
  • 49
  • 54
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,093
  • 2
  • 27
  • 42
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,436
  • 2
  • 12
  • 14