24

I think these are the common ways of passing the result of one command to the next one, as inputs.

How do these three work? Or what are some websites/URLs?

4 Answers 4

29

First things to type:

man find

man xargs

The find command prints results to standard output by default, so the -print option is normally not needed, but -print0 separates the filenames with a 0 (NULL) byte so that names containing spaces or newlines can be interpreted correctly.

The -exec option is something you can use instead of xargs - the find command executes a command for each item it finds.

The xargs command reads space- or newline-separated strings (typically from the find command, but they could come from anywhere) and executes some command for each string.
If xargs is run with a -0 option, it'll expect NULL-separated strings as output by find ... -print0

The advantage of xargs is that it can group the strings together, so that it only executes a command once or twice instead of n times.

So in the normal usage:

find start_directory -name '*.txt' | xargs ls -l 

find would list the filenames, and xargs would issue commands like:

ls -l file1.txt file2.txt file3.txt ... fileN.txt

which is faster than having your find command issuing:

ls -l file1.txt
ls -l file2.txt
ls -l file3.txt
ls -l ...
ls -l fileN.txt
11

Note that xargs is no more needed with current find implementations that probably all support this POSIX syntax:

find directory -name '*.txt' -exec ls -l {} + 

which is simpler and slightly faster than the xargs variant.

find directory -name '*.txt' | xargs ls -l 
4
  • xargs uses far fewer resources than 'find -exec' Sep 1, 2010 at 13:44
  • 8
    That's the other way around. Piping to xargs will use slightly more resources than -exec. You probably overlook the "+" terminator.
    – jlliagre
    Sep 1, 2010 at 15:32
  • xargs can use more than one processor... this is much more helpful when the command is more complicated than 'ls'... possibly something like a file conversion. Jan 22, 2021 at 0:27
  • @JosephFitzgerald Gnu xargs has this extension indeed but other xargs implementations might not as it isn't specified by POSIX. That was probably more relevant ten years ago than now though.
    – jlliagre
    Jan 22, 2021 at 1:00
2

See the following articles:

Linux and Unix find command tutorial with examples
xargs: How To Control and Use Command Line Arguments

2
  • 1
    at least one of those links is dead. Its better to just post the relevant code sample as well. Aug 22, 2017 at 15:32
  • @user5359531: The dead link was replaced. And I cannot reproduce such voluminous tutorials.
    – harrymc
    Aug 22, 2017 at 15:41
2

Make two files by

touch 'my file1' myfile2

find . -name "m*" | xargs ls -l (error)

find . -name "m*" -print0 | xargs --null ls - l (right outcome)

-print0 seperate the file names with space

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .