A
A
Asparagales2018-10-22 18:33:48
linux
Asparagales, 2018-10-22 18:33:48

What is the difference between the xargs command and a pipeline?

Hello.
Here is an example from a Linux command line tutorial:

The xargs command takes input from standard input and converts it into a list of arguments for the specified command. In this example, it could be used like this:

find ~ -type f -name 'foo*' -print | xargs ls -l
and further:
Here, the output of the find command is piped to the xargs command, which in turn constructs the argument list for the ls command and executes it.

However, my question is - isn't the pipeline doing the same thing - passing data from the standard output of the first command to the standard input of the second command as its arguments? Why would a pipeline need to pass data to xargs rather than directly to ls ? For example, the following example from the same tutorial only uses a pipeline:
ls -l /usr/bin | less
What is the difference between the two?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dmitry Shitskov, 2018-10-22
@Zarom

standard input and command arguments are two completely different things!

S
Saboteur, 2018-10-23
@saboteur_kiev

For those commands that need to turn a list of values ​​from a pipe into arguments, xargs turns a stdin pipe into a sequence of arguments.
Examples for understanding

$ # команда echo не работает с stdin
$ echo 1 2 3 4 5 | echo

$# команда echo работает с аргументами
$ echo 1 2 3 4 5 | xargs echo
1 2 3 4 5

$# команда cat работает с stdin
$ echo 1 2 3 4 5 | cat
1 2 3 4 5

$# команда cat работает и с аргументами, но при этом ищет файлы
$ echo 1 2 3 4 5 | xargs cat
cat: 1: No such file or directory
cat: 2: No such file or directory
cat: 3: No such file or directory
cat: 4: No such file or directory
cat: 5: No such file or directory

In addition, xargs allows you to process a pipe in parts, and also in parallel.

I
Ingvar, 2018-10-22
@take

this is a good question. I didn't bother myself with the difference either. somehow in practice, if the pipe | does not work, then xargs the
English segment explains: not all commands read standard input, for example,
it will give nothing
there are programs that do not read input from the pipe, but only input from the user or only parameters of their command line. so, echo understands the parameters of echo abcd . that's what xargs is for . It will convert its input into variables for the specified program:
it will give the desired result at the output,
or something like that)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question