Saturday, September 18, 2010

Kill Script Using Linux Shell (bash)

Here is a script written in bash that kills a process with the signature provided as a parameter.

NOTES:
- In RedHat Linux you can use /bin/sh as sh does not exist in Linux and it is pointing to bash instead
- In UBUNTU you need to specify /bin/bash as /bin/sh is pointing to dash by default
- I did not have a chance to test this script in other UNIX systems


#!/bin/bash

# Script name itself (we will ignore it, 
# as we do not want to kill our own script)
mysignature=$0

# Signature of a process to kill 
procsig=$1
echo Lookig to kill processes with signature :$procsig:

# Trim spaces 
read -rd '' param1 <<< "$procsig"

# Check that we suuplied a process signature, 
# and that it is not empty
if [ "$param1" = "" ]
then
  echo Need process name pattern
  exit 1
fi

echo Loking up process signature :$procsig:

# Get PID(s) of the process(es) to be killed
processes= \
 `ps auxwww | grep " $procsig" | grep -v grep | grep -v $mysignature | cut -c10-15`

if [ "$processes" = "" ]
then
  echo No process like  :$procsig: running
  exit 1
fi

echo Killing PIDs $processes

echo $processes | xargs -t kill

To run this script- create a file called (for example) stop_script.sh, copy the provided script into that file.

Run it (for example to kill all vi sessions) as follows

stop_script.sh "vi"

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).