Sunday, September 12, 2010

Kill Script Using Perl

Sometimes you need to have a process that kills other processes.
Here is a small perl script that kills all the processes with a particular pattern in the name (" vi" in this case).


#!/usr/bin/perl

@pids = `ps auxwww | grep " vi" | grep -v grep | cut -c10-15`;

foreach(@pids){
  $killcmd = "kill -9 " . $_;
  print "executing " . $killcmd;
  `$killcmd`;
}

NOTES
- ps auxwww returns all running processes with full information known to the system

- grep " vi" finds processes with pattern " vi" in the output of ps

- grep -v grep excludes grep itself (we do not want to kill our grep) as the pattern we are looking for exists in grep, it will be picked up as just another process to be killed

-cut -c10-15 returns only PIDs

Once the list of PIDs is created we can loop through it killing processes (use -9 if you want to kill immediately interrupting IO).

2 comments:

  1. what is . $_

    $_ is used for return arguments wahat is .

    ReplyDelete
  2. dot (.) means string concatenation in perl

    ReplyDelete