How to ignore xargs commands if stdin input is empty? How to ignore xargs commands if stdin input is empty? bash bash

How to ignore xargs commands if stdin input is empty?


For GNU xargs, you can use the -r or --no-run-if-empty option:

--no-run-if-empty
-r
If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension.


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


man xargs says --no-run-if-empty.