Dirname appears not to work with xargs

dirnameosxxargs

xargs and basename work together as I would expect:

$ printf '%s\n' foo/index.js bar/index.js baz/index.js | xargs basename
index.js
index.js
index.js

xargs and dirname, though, appear not to work together:

$ printf '%s\n' foo/index.js bar/index.js baz/index.js | xargs dirname
usage: dirname path

I would expect

foo
bar
baz

as output. What am I missing?

I'm on Darwin 18.2.0 (macOS 10.14.3).

Best Answer

dirname on macOS only takes a single pathname, whereas basename is able to work with multiple pathnames. It is however safest to call basename with a single pathname so that it does not accidentally try to remove the the second pathname from the end of the first, as in

$ basename some/file e
fil

When calling these utilities from xargs you may ask xargs to run the utility with a single newline-delimited string at a time:

printf '%s\n' some arguments | xargs -I {} basename {}

or,

printf '%s\n' some arguments | xargs -I {} dirname {}

You could also use xargs -L 1 utility rather than xargs -I {} utility {}.

Related Question