Unix.. extracting PIDs and kill command

LuDaCriS66

Platinum Member
Nov 21, 2001
2,057
0
0
I've got a piped command like so in a Bourne shell script..
/usr/ucb/ps -auxc | grep "$1$"| awk'{print $2}'> temp

but I'm not sure how to be able to extract the process ID numbers from there and use the kill command on the results given.
Do I need to make it somehow output each single result and then apply kill.. or can it do it to all?

any ideas?
 

Barnaby W. Füi

Elite Member
Aug 14, 2001
12,343
0
0
Easiest way:

pgrep "$1$" | xargs kill

:)

I'm not sure how standard pgrep is, but I have it on both debian and netbsd. As far as what you have above, it's doing basically what pgrep does: printing a list of pids, one per line. kill can take multiple pids as arguments, so you can pass them all at once. newlines work weirdly in shell and when you pass something that produces newlines as an argument (like echo `ls -1`), it'll turn the newlines into spaces.

What I'm getting to is that you can basically take what you have and pass it as an argument to kill, like:

kill `/usr/ucb/ps -auxc | grep "$1$"| awk '{print $2}'`

or:

/usr/ucb/ps -auxc | grep "$1$"| awk '{print $2}' | xargs kill

or even:

for pid in `/usr/ucb/ps -auxc | grep "$1$"| awk'{print $2}'`; do kill $pid; done

The last one will actually run kill for every single argument, while the other two will run one invocation of kill with the pids as the arguments. There's usually a bunch of ways to accomplish the same thing in shell ;)
 

chsh1ca

Golden Member
Feb 17, 2003
1,179
0
0
Alternately something like:
kill `pgrep "$1$"`
works just as well.

You will likely find numerous ways of doing it, but if you are missing pgrep, you can just use the same method as I supply above:
kill `ps auxc | grep "user" | awk '{print $2}'`
where 'user' is interchangable with your search criteria.
 

LuDaCriS66

Platinum Member
Nov 21, 2001
2,057
0
0
thanks guys :)

Didn't even think of using a For statement.. :eek: .. too many things to remember