tags:

views:

127

answers:

6

Hello,

I sometimes do this in my shell :

sam@sam-laptop:~/shell$ ps aux | grep firefox | awk '{print $2}'
2681
2685
2689
4645

$ kill -9 2681 2685 2689 4645

Is there a way I can transform the multiple lines containing the PIDs into one line separated by spaces ? (It's a little bit annoying to type the PIDs every time and I really would like to learn :) )

Thanks a lot.

+2  A: 
pids=""
for pid in $(ps aux | grep firefox | awk '{print $2}')
do
pids=" $pid"
done
kill -9 $pids
ennuikiller
Did you mean `pids="$pids $pid"` ? I do not see how this is working...
Pascal Cuoq
Thanks works like a charm :)
Samantha
+10  A: 

The easy way for this is using xargs

ps aux | grep firefox | awk '{print $2}' | xargs kill -9

This will invoke the kill command with all pids at the same time. (Exactly what you want)

Peter Smit
Great, i knew it then :)
Tom
+2  A: 

Use pkill instead. There is also a pgrep.

This will do what you want, and how much simpler can you get?

pkill firefox

Using the -9 option to pkill would be what you currently do; however, avoid SIGKILL:

Do not use this signal lightly. The process will not have any chance to clean up. It may leave behind orphaned child processes, temporary files, allocated locks, active shared memory segments, busy sockets, and any number of other resource state inconsistencies. This can lead to surprising and hard to debug problems in the subsequent operation of the system. [wlug.org]

And:

By the way, this is one reason you should not routinely use SIGKILL. SIGKILL should only be used when a process is hung and cannot be killed any other way. If you use a SIGTERM or SIGINT in the python script, you will see that mplayer WILL leave the terminal in a USABLE state. If you routinely use SIGKILL programs do not have a chance to clean up anything and can adversely affect your whole system in some situations.

SIGTERM is the default signal sent by the kill shell command. SIGINT is the signal sent from a terminal interrupt (control-C). [debian.org]

Roger Pate
thanks Roger, i'm looking into the man pages very helpful :)
Samantha
+3  A: 
    killall -9 firefox 
maxorq
works too :) thanks!
Samantha
+2  A: 

you can do it with just awk

ps -eo pid,args | awk 'BEGIN{s="kill -9 "}$2~/bash/{s=s" "$1} END{system(s)}'
ghostdog74
+2  A: 

I agree with all the other responses about using pkill, but, ... and instead of using xargs, ... you can pipe it to tr:

kill $(ps aux | grep [f]irefox | awk '{print $2}' | tr '\n' ' ')

Also, consider using the [f] so that you don't match the grep process itself.

nicerobot