-r argument to pipe (no argument for MacOS)- If no input is given to xargs, don’t let xargs run the utility – Unix & Linux Stack Exchange
Posted by jpluimers on 2021/07/28
TL;DR
There is a non-standard -r option to xargs that allows it to skip executing when there are no arguments at all.
On some operating systems, the -r is default.
MacOS has no -r, but does not execute xargs if there are no arguments given.
shell-tools to experiment with shell commands
Via the below answer:
- [WayBack] shell-toolbox/INSTALL at develop · kusalananda/shell-toolbox · GitHub
- at [WayBack] GitHub – kusalananda/shell-toolbox: Useful shell scripts for /bin/sh
* shell: Creates a shell for testing things in. This script is useful for testing things in an interactive environment other than your usual shell, or for testing things in a clean environment with automatic cleanup of any files left behind. Creates a "temporary interactive shell" with a temporary working directory (unless the "-d" flag is used to specify an existing directory) and clean environment. The working directory is removed when the shell exits (unless the "-k" or "-d" flag was used). The temporary working directory may also be pre-populated with the contents of an existing directory (using the "-s" flag). See "man 1 shell" after installation.
Long, maybe read
[WayBack] pipe – If no input is given to xargs, don’t let xargs run the utility – Unix & Linux Stack Exchange (thanks [WayBack] Kusalananda):
You are looking for the
-roption. This is a non-standard option which is often implemented (check yourxargsmanual).From the GNU
xargsmanual:
-r,--no-run-if-emptyIf 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.
From the manual on an OpenBSD system:
-rDo not run the command if there are no arguments. Normally the command is executed at least once even if there are no arguments.
On FreeBSD and macOS, this is the default behaviour.
xargson AIX and Solaris does not have a-roption, and it is unknown what the default behaviour is (I don’t have access to an AIX or Solaris system).
One work-around on systems with no
-rflag forxargs(and where running the utility at east once is the default behaviour) is to usesomething | xargs sh -c '[ "$#" -gt 0 ] && utility "$@"' sh(or something like it; note that the trailing
shis required) whereutilityis the utility that you’d like to run withxargs, and wheresomethingproduces some arguments.The short shell script
[ "$#" -gt 0 ] && utility "$@"tests whether it was given any arguments, and if so, it runs the utility with those arguments.…
On macOS,
-ris not an accepted option, but it is the default behaviour, as on FreeBSD.
–jeroen






Leave a comment