One irritation in xargs
's interface
Xargs is generally a nice command that more or less works right.
Some people could criticize Unix for needing it so much (which is
mostly a product of command line length limitations) and the need for -0
is a bit annoying,
but on the whole it's good. But xargs
has one little corner case
that is really annoying; as a bonus, it's even non-portable in an
irritating way.
Here it is, presented in illustrated form:
$ xargs echo does run </dev/null
Now the question: will this produce any output? In other words, does
xargs
run the command once even if there are no (extra) arguments
to give to it?
The answer is that it does in some but not all versions of xargs
:
- Solaris 10 runs
echo
once and has no option to disable this. - GNU findutils
xargs
(commonly used on Linux) normally runsecho
once but can turn this off with-r
aka--no-run-if-empty
. - FreeBSD doesn't run
echo
and has no option to change this. Recent versions accept-r
for compatibility with GNUxargs
; old versions don't. - OpenBSD runs
echo
once but can turn this behavior off with-r
. - Mac OS X doesn't run
echo
and has no-r
argument.
Based on the current manpage, NetBSD xargs
behaves the same as
FreeBSD xargs
(including accepting a do-nothing -r
argument).
The Single Unix Specification for xargs
is
rather ambiguous about what behavior is allowed or required; it
certainly never definitely states things either way (and it has no
-r
argument). My close reading leads me to believe that SuS
probably requires xargs
to run echo
once, but only by implication.
This would match what I believe is historical behavior (as suggested
by Solaris, which is very historical). I assume that at some point
FreeBSD decided that this historical behavior was a bad idea and
changed it.
My view is that (historical) xargs
behavior is stupid and is a bear
trap waiting to bite you in unusual situations. You almost never
want to run the xargs
command even if there is nothing for it to
operate on. In many situations and usages you'll get odd results if
there is nothing to operate on; in extreme cases you may get dangerous
explosions. This is an easy issue to overlook because everyone almost
always uses xargs
in situations that do generate arguments list
(especially when you're testing your command lines or scripts). In fact
I suspect that many people using xargs
on Linux, Solaris, and OpenBSD
machines don't even know about this potential gotcha, which sort of
proves my point.
(This entry is yet another illustration of how a simple entry idea can
turn out much more interesting than I expected when I started writing
it. Before I started actually checking systems I would have confidently
told you that all versions of xargs
would run echo
once; I had no
idea how tangled the actual situation was.)
|
|