78

How can I kill a process based on its command line arguments? killall, pgrep, and pkill seem to only work based on the process name.

I need this to be able to differentiate between a number of applications running inside Java virtual machines, where java is the process name for all of them and the actual application name can be found by looking at the command line arguments.

This can be done manually with ps aux | grep myapp.jar and then manually killing the pid from the output, but I'd like a command to do something equivalent automatically.

Michael Mrozek
  • 93,103
  • 40
  • 240
  • 233

4 Answers4

106

pgrep/pkill take a -f flag. From the man page:

-f    The pattern is normally only matched against the process name.
      When -f is set, the full command line is used.

For example:

$ sleep 30& sleep 60&
[1] 8007
[2] 8008

$ pkill -f 'sleep 30'
[1]  - terminated  sleep 30

$ pgrep sleep
8008
Michael Mrozek
  • 93,103
  • 40
  • 240
  • 233
  • +1, but my bash 4.1.5 doesn't work for a colon after an ampersand (as in the example's first line)... bash: syntax error near unexpected token ';' ... It does work in a case statement when the ampersand is followed by ;; ... maybe you are using a different shell(?) – Peter.O Feb 07 '12 at 20:07
  • @jw013 I was actually using zsh, which supports the syntax I used. Leaving it out works in both though, so I removed it – Michael Mrozek Feb 08 '12 at 06:36
  • @MichaelMrozek ok nvm then :) I wonder if unix.SE has a higher proportion of zsh users than elsewhere - I only seem to find zsh users here. – jw013 Feb 09 '12 at 06:58
  • 1
    pgrep and pkill take a regular expression. So pkill -f 'sleep .0' would kill sleep 30 and sleep 60 but not sleep 35. If you want to match any parameter do pkill -f 'sleep .* myArg'. – Ryan Shillington Jul 02 '21 at 14:51
  • pkill -f ".*java .* org.apache.rocketmq.console.App" This help to kill a java process with given args. – Eric Aug 04 '21 at 09:43
5

Replace argument below with a regular expression that must much the full command line of a process:

kill `ps -eo pid,args --cols=10000 | awk '/argument/ && $1 != PROCINFO["pid"] { print $1 }'`
4

You can use htop to view all currently running processes with their command line arguments and to kill a selected process.

Jan Henke
  • 1,077
0

If you don't have pkill or whatever, just use proc/[1-9]*/cmdline

grep -a myapp.jar /proc/[1-9]*/cmdline|tr '\0' ' '|grep -v grep|awk -F/ '{print $3}'
ikrabbe
  • 2,163