xargs
Shell (~bash)
So, you want to sling command line like a boss, eh? I’ve heard it said and believe it more and more each day that the core things you should learn on the command line are find
, xargs
, grep
, sed
, cut
, while
, and echo
. (add wc
, sort
, and history
to taste)
Of these, the one I see ignored most often is xargs
. So, let’s check it out:
>xargs
1
2
3
4
^D
1 2 3 4
Technically, xargs
“reads space, tab, newline and end-of-file delimited strings from the standard input and executes a command with the strings as arguments”…and the default command is echo
.
So, in the above, we invoke xargs
, it starts listening to stdin, we provide a list of numbers separated by newlines, ^D
signals the end of the input, and xargs
turns our numbers into a space-separated list that gets passed to echo. Voila!
We could also separate things with tabs or spaces. We can even mix them:
>xargs
1
2 3
4 5
^D
1 2 3 4 5
In practice, xargs
usually takes a list of things generated by some other command (like find
) and iterates a command over them. What if we wanted to delete all the files larger than 100MB in the current directory tree?
>find . -size 100M | xargs rm
(If you’re really worried that this will hiccup on filenames with a space in them, you can use find -print0
and xargs -0
instead. Those create/consume null delimited lists instead. In practice, I’ve never had that be a problem.)
What if we wanted to clean up our project a little bit?
>find . -name *.o | xargs rm -rf
…and so on…
CAUTION: It’s really easy to combine find
, xargs
, and rm
in clever ways that will do terrible things to your system. Measure twice, rm
once.