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"

No comments:

Post a Comment