I have a script that may in some circumstances have nothing on stdout. At the end of the script, I pass the lines I have to another command using xargs. My problem is, when there is nothing on stdout, I get the typical "Usage: program arg1 arg2" error message.

How can I avoid this?

up vote 13 down vote accepted

You need an -r or --no-run-if-empty options.

Keep in mind that this particular behavior is hard to make cross-platform. BSD versions of xargs run with -r by default. GNU version needs it. FreeBSD version of xargs ignores -r flag for compatibility with GNU. Mac OS X version does not even accept the flag and throws an error illegal option.

You might then choose to use an OS detection based on $OSTYPE to write a cross-platform script. Even better, try to detect the behavior of xargs itself. Run it with -r and if that fails (status code > 0), run it without -r.

A lesson in why you should read the man pages…

The -r or --no-run-if-empty flags are my friend.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.