4

when I execute xargs -n2, enter x x x x x and hit Enter, I get only 4 x back:

$ xargs -n2
x x x x x 
x x 
x x 

But, when I pipe the x x x x x into the same command, I get the same amount of x back:

$ echo x x x x x | xargs -n2
x x 
x x 
x

why is it that in the first scenario the amount of arguments is either rounded up or rounded down ?

terdon
  • 234,489
  • 66
  • 447
  • 667
Abdul Al Hazred
  • 25,760
  • 23
  • 64
  • 88
  • 1
    in first case, what happen if you types in a second line with a b c ? or Ctrl-D ? – Archemar Mar 24 '15 at 12:26
  • 3
    In the first case it's still waiting for input so if you hit `Ctrl+D` it'll print the remaining `x` too. See [How to signal the end of stdin input](http://unix.stackexchange.com/q/16333) – don_crissti Mar 24 '15 at 12:31

1 Answers1

5

In the first line, xargs still waits for the second argument or an end of the input. After pressing Ctrl-D xargs continues with the rest and you will see the 5th x as single argument.

This example may explain the behavior:

(echo "x x x x x"; sleep 5; echo "x") | xargs -n2

Output:

x x
x x
x x     # after 5 seconds

After the 6th x in the second echo statement the input stream is finished and xargs finally has the second argument, but until then it waits the 5 seconds.

chaos
  • 47,463
  • 11
  • 118
  • 144
  • Presumably this is because of the `-n 2 ` which forces `xargs` to expect arguments that are multiples of 2 right? – terdon Mar 24 '15 at 13:39
  • `xargs` can also continue with one argument if the second argument would exceed a specific size (`-s`). But, also in that case `xargs` would wait until that arguemnt came. – chaos Mar 24 '15 at 13:45