Handy little util that searches currently running processes and kills those matching a string or regexp. It was created as a result of me getting annoyed with continually having to use:
for PROCESS in `/bin/ps aux | grep [n]etscape | sed -e 's/[[:blank:]]\ +{2,\}/ /g' | cut -f2 -d' '`; do kill $PROCESS; done;
to achieve the same effect.
#!/usr/bin/perl -w require 5; use strict; use Getopt::Std; use vars qw(%opts $term @processes $user $signal); getopts('ht:s:u:mn', \%opts); sub usage(){ print <<EOF; Usage: $0 [options] [search term] Example: $0 -m -s STOP -t netscape -h : displays this help screen -t TERM : search for TERM -n : do not kill anything, merely list process ids -s SIGNAL : send processes SIGNAL (default is TERM) -m : only kill processes owned by you -u USER : only kill processes belonging to USER If no options are given, option t is assumed if a search term is prese +nt, option h otherwise. EOF exit; } if ($opts{'h'}){ usage(); } $user = $opts{'u'} || ($opts{'m'} && getpwuid($<)); if ($term = ($opts{'t'} || $ARGV[0])) { print "Processes matching \'$term\'", defined($user) ? " and owned + by \'$user\'": "" ,": "; @processes = map { m@^(\w+)\s+(\d+)\s+[\d\.]+\s+[\d\.]+\s+.+$term. +*$@ && ($2 != $$) && (!(defined ($user)) || ($1 eq $user))? $2 : () } + `ps aux`; if (@processes){ print "@processes\n"; } else { print "none\n"; exit; } if (!$opts{'n'}){ $signal = defined($opts{'s'}) ? $opts{'s'} : 15; kill $signal, @processes; print "Done killing processes\n" } } else { usage(); }

Replies are listed 'Best First'.
RE: killgrep
by merlyn (Sage) on Aug 15, 2000 at 17:48 UTC
    Please don't default to 9. If you kill -9, the process doesn't get a chance to clean up. Default to 15. If you want a "super kill", then do a real one that sequences through 15, waits a few seconds, then 2, then wait a few seconds, then 1, then waits a few seconds, and only then does a 9. That's what shutdown does. Much nicer.

    -- Randal L. Schwartz, Perl hacker

      Good point. That's what I get for coding out of sheer annoyance ;-) (script changed)