0

I want to look for a specific process and then kill it (in a script).

I'm doing ps -fu user | grep matching_string but this is returning me two rows: one for the expected pid and another for the pid of the grep.

If the result were two columns, I would use awk to pick the first one. But I don't know how to pick the first result when they are returned as row.

2 Answers2

2

How about pkill?

pkill -U user-id process-name
ElmoVanKielmo
  • 10,907
  • 2
  • 32
  • 46
1

You can use this trick:

ps -fu user | grep matching_strin[g]

This way, the grep match won't appear.

How does it work? (see Find and kill a process in one line using bash and regex for more detail).

  • With ps -fu user | grep matching_string it lists all the processes having grep matching_string, so that includes the grep itself.
  • Doing ps -fu user | grep matching_strin[g] you add a regular expression that makes grep skip the grep itself. Why? Because the process name is grep matching_strin[g] and does not match the literal matching_string.
Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • This worked. For example I wrote [j]ava and it didn't show the grep command. I'm going to accept yours, as it was the first I read and worked. 7 mins left. –  Mar 27 '14 at 12:31
  • Yes! You can place it whenever you want, the point is to add a regex so that `grep` does not match its own process. – fedorqui Mar 27 '14 at 12:34