Q:

How to ignore xargs commands if stdin input is empty?

Consider this command:
ls /mydir/*.txt | xargs chown root

The intention is to change owners of all text files in mydir to root
The issue is that if there are no .txt files in mydir then xargs thows an error saying there is no path specified. This is a harmless example because an error is being thrown, but in some cases, like in the script that i need to use here, a blank path is assumed to be the current directory. So if I run that command from /home/tom/ then if there is no result for ls /mydir/*.txt and all files under /home/tom/ have their owners changed to root.
So how can I have xargs ignore an empty result?

A:

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.

A:

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 fewer
ls /empty_dir/ | xargs -L10 chown root # chown executed every 10 lines or fewer
ls /empty_dir/ | xargs -i cp {} {}.bak # every {} is replaced with the args from one input line
ls /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 -is
SunOS sun4v
$ xargs -n1 echo blah < /dev/null

$ uname -is
Linux x86_64
$ xargs --version | head -1
xargs (GNU findutils) 4.7.0-git
$ xargs -n1 echo blah < /dev/null
blah

A:

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

