Saturday, April 28, 2012

xargs and exec


find . -name H* -exec ls -l {} \; executes the command ls -l on each individual file.

find . -name H* | xargs ls -l constructs an argument list from the output of the find commend and passes it to ls.

consider if the ouput of the find command produced:
H1
H2
H3

the first command would execute
ls -l H1
ls -l H2
ls -l H3

but the second would execute
ls -l H1 H2 H3


As reborg mentioned, the second is faster because xargs will collect file names and execute a command with as long as a length as possible. Often this will be just a single command.  

This is where -exec breaks down and xargs shows its superiority. When you use -exec to do the work you run a separate instance of the called program for each element of input. So if findcomes up with 10,000 results, you run exec 10,000 times. Withxargs, you build up the input into bundles and run them through the command as few times as possible, which is often just once. When dealing with hundreds or thousands of elements this is a big win forxargs.

No comments:

Post a Comment