xargs -n 1 - Invoke command for every provided argument

August 20, 2014

Intro

From the man page of xargs:

The xargs utility reads space, tab, newline and end-of-file delimited strings from the standard input and executes utility with the strings as arguments.

Useful when used with tools that can't read piped content by themselves, eg. ls.

Robins-MacBook-Pro-2:/ robin$ echo /opt | ls Applications System cfg dev lost+found private tmp Benutzerinformationen Users collectionCache.bnk docs mach_kernel sbin usr Library Volumes cores etc net share var Network bin data home opt tests www Robins-MacBook-Pro-2:/ robin$
Robins-MacBook-Pro-2:/ robin$ echo /opt | xargs ls X11 Robins-MacBook-Pro-2:/ robin$

TIL

xargs is capable of invoking the provided utility not once with all the arguments provided, but also invoking the utility e.g. once per argument.

Example utility invoked once with all arguments

Robins-MacBook-Pro-2:/ robin$ echo /opt /dev /Volumes | xargs echo /opt /dev /Volumes Robins-MacBook-Pro-2:/ robin$

Example utility invoked once per argument

Robins-MacBook-Pro-2:/ robin$ echo /opt /dev /Volumes | xargs -n1 echo /opt /dev /Volumes Robins-MacBook-Pro-2:/ robin$

Usecase

I used it to created a lot of copies of the same file at once.

Robins-MacBook-Pro-2:cpfoo robin$ ls source Robins-MacBook-Pro-2:cpfoo robin$ echo destination-{1..5} | xargs -n1 cp source Robins-MacBook-Pro-2:cpfoo robin$ ls destination-1 destination-2 destination-3 destination-4 destination-5 source Robins-MacBook-Pro-2:cpfoo robin$

This snippet also makes use of a feature called brace expansion, which I'll probably also cover sometimes.