Originally posted by jbsnake
in this example i'm going to scroll through the output of the ps command looking for a specific running process. once found i will kill that process
Code:
# the first line pipes the output from ps aux to awk
# using the -v (variable) tag. The variable tag is creating a variable called proc
# and it is being populated with whatever is being passed to the script on the command line
# inside the {} we have an if statement, it's seeing if either the 11th position
# is like (~) what is stored in the variable proc, if it is,
# print whatever is in the second position (the process ID) into a file called term.tmp
ps aux | awk -v proc=$1 '{if ($11 ~ proc || $12 ~ proc) print $2;}' > term.tmp
# once all that above is done (whew), we populate our variable proc with whatever process ID we got
proc=`cat term.tmp`
# we see if there is anything inside the variable proc
if [[ ${#proc} != 0 ]]
then
# if it contains anything, we kill it :)
echo "Killing program '$1' which is process $proc..."
kill $proc
# if that finished without error, say so
if [[ $? == 0 ]]
then
echo "*** Terminated ***"
fi
# remove the file we created
rm term.tmp
else
# if the variable doesn't contain anything, say so
echo "*** Program doesn't exist! ***"
fi
fun huh?
now keep in mind, this is successful IF there are not more than one process running with the same name.
in other words...you wouldn't be able to use this to close the apache server since there are like 6 instances that run at any given time. to test this, open 'kate' or some other simple program and try
Code:
<- jb:/home/jbsnake -> scripts/awkKill kate
Killing program 'kate' which is process 22130...
*** Terminated ***
<- jb:/home/jbsnake ->
it's a neat little app (or function in another app

)