53

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?

Tomáš Zato
  • 1,776

3 Answers3

67

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
cuonglm
  • 153,898
  • 6
    Nothing to do with space versus newline. Simply because kill doesn't read arguments on stdin. – Mikel Jun 20 '14 at 06:23
  • @Mikel: My mistake, fixed. – cuonglm Jun 20 '14 at 06:26
  • is there a list of commands which xargs will build arguments for? – alchemy Mar 25 '20 at 16:24
  • @alchemy any command you passed to xargs – cuonglm Mar 27 '20 at 05:20
  • Thanks, but it doesn't seem to work for Tail sudo tail -F /var/log/syslog | xargs echo. It will be extraordinarily handy for other things like Mail cat file | grep keyword | xargs echo | mail a@a.com without having to store the output of grep into a variable using Read, which can only do that in a subshell and buries the variable in Bash. (https://unix.stackexchange.com/a/365222/346155) – alchemy Mar 27 '20 at 16:10
  • If pgrep won't find the process, the parameter -f will not only search the processname for the expression but instead the whole line from ps. Example: pgrep -f "yarn serve" | xargs kill – JackLeEmmerdeur Apr 10 '21 at 17:48
35

This should work:

pkill name

I also suggest reading the man page.

12

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)
Mikel
  • 57,299
  • 15
  • 134
  • 153