Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I want to kill root owned processes containing foo in the process name

sudo sh -c "ps aux | grep [f]oo  | awk '{print $2}' | xargs kill -15"

this command fail as awk and xargs are ignored.

sudo sh -c "ps aux | grep [f]oo  | awk '{print $2}' | xargs kill -15"

so kill receives bad args

kill pid ...              Send SIGTERM to every process listed.
  kill signal pid ...       Send a signal to every process listed.
  kill -s signal pid ...    Send a signal to every process listed.
  kill -l                   List all signal names.
  kill -L                   List all signal names in a nice table.
  kill -l signal            Convert between signal numbers and names.
share|improve this question
2  
Does your system not have pkill? –  Cry Havok Jan 11 '13 at 22:02
    
What have you tried (to get this to work)? Standard trouble-shooting technique: break things down to see what part(s) are not behaving the way you expect. Does ps aux | grep "[f]oo" show you the processes you’re interested in? Does ps aux | grep "[f]oo" | awk '{print $2}' show you their PIDs? (P.S. I recommend putting [f]oo in quotes.) –  Scott Jan 11 '13 at 22:12
    
Thanks, I can see the processes and the pids –  Dave Jan 11 '13 at 22:19
    
So how about ps aux | grep "[f]oo" | awk '{print $2}' | xargs /bin/echo kill –15? –  Scott Jan 11 '13 at 22:41
    
And what do you mean “awk and xargs are ignored”? Are you getting error messages that you’re not telling us? –  Scott Jan 11 '13 at 22:44

3 Answers 3

up vote 1 down vote accepted

This is an ugly hack, and kill will complain, but it works (for me, at least):

sudo kill `ps -ae | grep foo` &>/dev/null

The &>/dev/null part is optional; include it if you do not want to see all of kill's complaints.

I know there is probably a better way of doing this, but this is what I use.

share|improve this answer

I believe your real problem lies in the quoting. Within double quotes $2 is expanded before it is even passed to sh. The single quotes as used in your code do not insulate this because they are just quoted characters. Try one of these quoting methods:

sh -c 'ps aux | grep [f]oo | awk '\''{ print $2 }'\'

sh -c $'ps aux | grep [f]oo | awk \'{ print $2 }\''

sh -c "ps aux | grep [f]ox | awk '{ print \$2 }'"

share|improve this answer
    
Very useful, thankyou very much –  Dave Feb 6 '13 at 7:15

As already mentioned pgrep and pkill are your friends:

sudo pkill `pgrep -u root foo`

If for some reason you do not have pgrep and pkill, you can do something like this:

for n in $(ps -u root | grep foo | cut -d ' ' -f 2); do sudo kill $n; done
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.