Hacker News new | ask | show | jobs
by laughing_man 8 days ago
Depending on the actual command, this can be far slower and less efficient than xargs. You're creating a separate process for each invocation of bar when a lot of commands will take many targets for a single invocation.

Try this with find and grep vs xargs. There's a big difference.

1 comments

3 reasons against that:

* in a lot of cases the performance just doesn't matter

* xargs gets you the spaces in filenames landmine

* some commands don't even support multiple target filename arguments

For scripts in long term use, yeah, sure, figure out xargs maybe. Any other situation with a "| while read" solution, especially on an interactive session, is an oddball and simplicity wins.

>* xargs gets you the spaces in filenames landmine

Ignorance of xargs gets you the landmine.

Understanding of xargs, helps you complete the mission without blowing off limbs.

    $ find . -name "Some Files With Spaces*.txt" -print0 | xargs -0 -I {} echo "Processing: {}"  # landmine avoided
cf. sibling, find is not the only thing to pipe from.
xargs supports null termination.

While it's true not every command supports multiple targets, presumably you know if you're using one of those commands.

xargs sure does support null termination.

Does whatever I'm piping into it though? It's "find" in maybe 30% of cases for me, no more, and null termination is not exactly common in other tools.

I'm not sure what you're trying to say. If you need null termination you're going to be a lot better off adding it at the source (say, with sed) than trying to make a while loop work in a shell script. If you don't need null termination, then... don't use it.
I am saying I have a whole bunch of other (not find) sources of items (not even filenames necessarily) that I need to loop over, none of which do null termination on output. It's an item per line, with spaces unescaped. I would either need "| tr '\n' '\0' | xargs -0" or "| xargs -d '\n'".

Considering the body of a while loop is more flexible too, I spend the brain capacity on remembering the details on that rather than xargs.

I'm well aware xargs is sometimes called for, but it's rare and when it happens I go look up the man page.