Thursday, November 17, 2011

Killgrep - Kill a process by part of its name

We know the command kill that can kill a process by its id, and we know killall that can stop the processes by its full name. What if we need to kill a process by some part of its name and/or arguments. A simple killgrep script can do and here is how it is done:


#!/bin/sh

# killgrep: Usage: killgrep server.py 
# will kill the process running like "python server.py"

echo $1

if [ -z "$1" ]; then
 echo "killgrep: "
 exit 1
fi

PROC=`ps auxwww | grep "$1" | grep -v grep | wc -l`
if [ $PROC = "0" ]; then
 echo "killgrep: None killed"
 exit 1
fi

PROC=`ps auxwww | grep "$1" | grep -v grep | perl -e '$_=<>; @u = split; print $u[1]' -`
if [ ! -z $PROC ]; then
 echo "killgrep: Stopping process $PROC"
 kill $PROC
fi

No comments:

Post a Comment