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:
On most systems (if
/proc
is not mounted withhidepid
) you don't needroot
privilege forps
.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'
There is no use in
grep
filtering input forawk
.awk
can do that pretty well on its own:awk '/wget/ {print $2}'
(or, due to theps
problem:awk '/[w]get/ {print $2}'
)Instead of filtering
ps
output and piping PIDs tokill
you could just usekillall wget
You would call
sudo
once forawk
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 fromawk
but not this way. You need thisawk
function:system(cmd-line)
If you want to use
ps
andkill
then do it this way: