Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.

share|improve this question

migrated from stackoverflow.com Feb 7 '12 at 17:34

This question came from our site for professional and enthusiast programmers.

3 Answers 3

up vote 14 down vote accepted

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
share|improve this answer
    
+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 7 '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 8 '12 at 6: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 9 '12 at 6:58

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 }'`
share|improve this answer

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.