How to use xargs to invoke an executable once for each argument
You might have used xargs before like this:
ls *.rb | xargs echo
This will invoke echo
once, with all the files passed in.
But what if you want to invoke echo
one time for each file? The answer is very easy and not very clearly described in the docs. From man xargs
-n number
Set the maximum number of arguments taken from standard input for each invocation of utility. An invocation of utility will use less than number standard input arguments if the number of bytes accumulated (see the -s option) exceeds the specified size or there are fewer than number arguments remaining for the last invocation of utility. The current default value for number is 5000.
No one will blame you for not immediately recognizing that this means if you use -n1
, that will simply invoke the executable once per input.
ls *.rb | xargs -n1 echo
tada!