27

I have noticed that | is used to send results of first command to the another. I would like to kill all processes that match a name.
This is what pgrep normally does:

$ pgrep name
5089
5105

And multiple arguments seem to work with kill:

sudo kill 5089 5105

But this is wrong:

pgrep name | kill

So how to do it properly?

  • 3
    pkill. And if that didn't exist, kill $(pgrep ...). – Mikel Jun 20 '14 at 6:18
  • I wasn't only asking about because of those specific commands but also to get better understanding of the command chaining. But as I can see from the question score, questions meant to understand are unwelcome... – Tomáš Zato Jun 20 '14 at 6:25
  • If you want to make the question more general, and ensure it's not a duplicate, I can vote it up. – Mikel Jun 20 '14 at 6:34
  • Sorry, accidentally deleted my previous comment. I'm on a tablet and this site has really small buttons next to each other. – Mikel Jun 20 '14 at 6:50
  • I was just saying that I downvoted because your question didn't seem to be asking anything you couldn't have learned from man pgrep. The downvote button says it's for when a question shows no research effort, and I couldn't see any in your question. Sorry if that seemed harsh. – Mikel Jun 20 '14 at 6:52
38

Try this:

pgrep name | xargs kill

If you use pgrep name | kill, the ouput of pgrep name is feed to stdin of kill. Because kill does not read arguments from stdin, so this will not work.

Using xargs, it will build arguments for kill from stdin. Example:

$ pgrep bash | xargs echo
5514 22298 23079
  • 5
    Nothing to do with space versus newline. Simply because kill doesn't read arguments on stdin. – Mikel Jun 20 '14 at 6:23
  • @Mikel: My mistake, fixed. – cuonglm Jun 20 '14 at 6:26
17

This should work:

pkill name

I also suggest reading the man page.

4

To answer the general rather than the specific...

Pipes are for passing output from one program as input to another program.

It looks like you're trying to use one program's output as command line arguments to another program, which is different.

To do that, use command substitution.

For example if you want to run

sudo kill 5089 5105

And you have a command pgrep name that outputs 5089 5105

You put them together like

sudo kill $(pgrep name)
  • Thanks a lot. I hope this will help other beginners too. – Tomáš Zato Jun 20 '14 at 7:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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