Search code examples
linuxshellpsfalse-positive

How do I match and kill a specific process without accidentally including unrelated processes?


I have two Tomcat processes, one is called event-ws, another is called app-event-ws. I sometimes need to kill event-ws from a shell script:

ps -ef | grep -w event-ws | grep -v grep

The above will find and kill both of them; how can I find exactly find one of them?


Solution

  • pgrep / pkill are the best tools to use in this case, instead of ps:

     pgrep -x event-ws   # match by executable filename 'event-ws'; print PID
     pkill -x event-ws   # match and kill
    

    Each command matches process(es) whose executable filename is event-ws exactly (-x) (irrespective of whether a directory path prefix was used when the executable was launched).

    Note, however, that your pgrep / pkill implementation may limit the name to 15 characters - both when matching and in its output.

    pgrep simply prints the matching PID(s) (process ID(s)), whereas pkill kills the matching process(es).


    If, by contrast, you need to match by a part of the full command line, use the -f option with a regular expression:

    pgrep -f '/event-ws/' # match by part of the full command line; print PID and name
    pkill -f '/event-ws/' # match and kill
    

    If you add -l to the pgrep command, the full command line of matching process(es) is printed instead of just the process name.