How to ignore xargs commands if stdin input is empty?
Users of non-GNU xargs may take advantage of -L <#lines>
, -n <#args>
, -i
, and -I <string>
:
ls /empty_dir/ | xargs -n10 chown root # chown executed every 10 args or fewerls /empty_dir/ | xargs -L10 chown root # chown executed every 10 lines or fewerls /empty_dir/ | xargs -i cp {} {}.bak # every {} is replaced with the args from one input linels /empty_dir/ | xargs -I ARG cp ARG ARG.bak # like -i, with a user-specified placeholder
Keep in mind that xargs splits the line at whitespace but quoting and escaping are available; RTFM for details.
Also, as Doron Behar mentions, this workaround isn't portable so checks may be needed:
$ uname -isSunOS sun4v$ xargs -n1 echo blah < /dev/null
$ uname -isLinux x86_64$ xargs --version | head -1xargs (GNU findutils) 4.7.0-git$ xargs -n1 echo blah < /dev/nullblah