Search code examples
bashshellcygwinxargs

Making xargs work in Cygwin


Linux/bash, taking the list of lines on input and using xargs to work on each line:

% ls -1 --color=never | xargs -I{} echo {}
a
b
c

Cygwin, take 1:

$ ls -1 --color=never | xargs -I{} echo {}
    xargs: invalid option -- I
    Usage: xargs [-0prtx] [-e[eof-str]] [-i[replace-str]] [-l[max-lines]]
           [-n max-args] [-s max-chars] [-P max-procs] [--null] [--eof[=eof-str]]
           [--replace[=replace-str]] [--max-lines[=max-lines]] [--interactive]
           [--max-chars=max-chars] [--verbose] [--exit] [--max-procs=max-procs]
           [--max-args=max-args] [--no-run-if-empty] [--version] [--help]
           [command [initial-arguments]]

Cygwin, take 2:

$ ls -1 --color=never | xargs echo
a b c

(yes, I know there's a universal method of ls -1 --color=never | while read X; do echo ${X}; done, I have tested that it works in Cygwin too, but I'm looking for a way to make xargs work correctly in Cygwin)


Solution

  • Use the -n argument of xargs, which is really the one you should be using, as -I is an option that serves to give the argument a 'name' so you can make them appear anywhere in the command line:

    $ ls -1 --color=never | xargs echo
    a b c
    $ ls -1 --color=never | xargs  -n 1 echo
    a
    b
    c
    

    From the manpage:

       -n max-args
              Use at most max-args arguments per command line
    
       -I replace-str
              Replace occurrences of replace-str in the initial-arguments with names read from standard input.