Kill several processes using awk tools

awkgrepkill

I want to stop several processes using awk.My command is like this:

sudo ps -ef|grep wget |grep -v grep|awk '{print $2;sudo kill -STOP $2}'

I want to stop all processes which is running wget. $2 of awk means the pid of each process.But I find that it doesn't work.The state of process remains the same.They are still running.

Instead , I modified this command:

sudo ps -ef|grep wget |grep -v grep|awk '{print $2}'|xargs sudo kill -STOP

it works! So , anyone can tell me the difference of them ?

Best Answer

There is a lot to be improved about your approach:

  1. On most systems (if /proc is not mounted with hidepid) you don't need root privilege for ps.

  2. There is no need for two grep instances just to get rid of the first in the process list. Do this instead: grep '[w]get'

  3. There is no use in grep filtering input for awk. awk can do that pretty well on its own: awk '/wget/ {print $2}' (or, due to the ps problem: awk '/[w]get/ {print $2}')

  4. Instead of filtering ps output and piping PIDs to kill you could just use killall wget

  5. You would call sudo once for awk and not once per input line.

The main problem in your first pipeline is the awk command: awk '{print $2;sudo kill -STOP $2}'. You can run external commands from awk but not this way. You need this awk function: system(cmd-line)

If you want to use ps and kill then do it this way:

kill -STOP $(ps -ef | awk '/[w]get/ {print $2}')
Related Question