How to ignore xargs commands if stdin input is empty?

HyderA picture HyderA · Nov 28, 2011 · Viewed 43.6k times · Source

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?

Answer

Sven Marnach picture Sven Marnach · Nov 28, 2011

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.