#!/bin/sh
#NAME
#  Kill - Send a signal to a process that matches a pattern
#SYNOPSIS
#  Kill      pattern..
#  Kill -SIG pattern..
#
#DESCRIPTION
#  This script runs ps and kills the processes that match the pattern(s).
#
#CONFIG
#  Different options are needed on different systems:
     OPT=uwax	# Linux and POSIX
#    OPT=gawux  # BSD, OSX
#    OPT=-elf   # Sys/V 
#  You may also need to change the field used by the cut command:
     FLD=3
#  Make sure we get the right commands:
     GRP=/usr/egrep
     SED=/usr/sed
     CUT=/usr/cut
#
#WARNINGS
#  It is very easy to kill more than you intended to kill.  Note that on some
#  Unix  systems,  the  "kill"  command  doesn't  accept  symbolic  names for
#  signals; if yours is like this, then change the default '-TERM' to  '-15'.
#  The  -<sig>  arg  may  only be omitted when there's just a single pattern,
#  because if there are two or more args,  the  first  is  assumed  to  be  a
#  signal.   On  OSX, you'll have to rename this program, due to the caseless
#  file system.
#
#AUTHOR
#  (C) 1984, 1987, 1995, 1998, 2000, 2004 by John Chambers <jc@trillian.mit.edu>
#  (I've made lots of slight tweaks for lots of systems' ps commands. ;-)
#  You can use this freely for any purpose whatsoever.
#
#  I really should rewrite this in perl to get rid of the system dependencies.

if [ $# -lt 1 ];then echo Usage: $0 -signal pattern;exit 1;fi
if [ $# -lt 2 ];then S='-TERM'; else S="$1";shift;fi
for p
do	PP=`ps $OPT \
		| $GRP "$p" \
		| $SED -e "s/^/ /" -e "/ $$ /d" -e "/ egrep /d" -e 's/  */#/g' \
		| $CUT -d# -f$FLD`
	echo kill $S $PP
	if [ -n "$PP" ];then
		kill $S $PP
	fi
done

exit 0
