Which is equivalent to xargs -r in OsX

Are they equivalent in OSX for xargs -r on Linux? I am trying to find a way to intercept a channel if there is no data.

For example, imagine that you are doing the following:

 touch test cat test | xargs -r echo "content: " 

This does not give any result, because xargs interrupts the channel.

Is there any hidden xargs option or something else to achieve the same result in OSX?

+8
source share
6 answers

You can use test or [ :

 if [ -s test ] ; then cat test | xargs echo content: ; fi 
+2
source

The POSIX standard for xargs provides that the command will be executed only once, even if there are no arguments. This is a nuisance, so GNU xargs has the -r option. Unfortunately, neither BSD (MacOS X) nor other major Unix versions (AIX, HP-UX, Solaris) support it.

If it’s extremely important for you, get and install GNU xargs somewhere where your environment finds it without affecting the system (so do not replace /usr/bin/xargs unless you are a brave person than me, but /usr/local/bin/xargs may be OK or $HOME/bin/xargs or ...).

+2
source

There is no standard way to determine if the xargs you are working on are GNU or not. I set $gnuargs both true and false, and then a function that replaces xargs and does the right thing.

On Linux, FreeBSD, and MacOS, this script works for me. The POSIX standard for xargs requires that a command be executed once, even if there are no arguments. FreeBSD and MacOS X violate this rule, so no -r is needed. GNU finds this annoying and adds -r . This script does the right thing and can be improved if you find a version of Unix that does it differently.

 #!/bin/bash gnuxargs=$(xargs --version 2>&1 |grep -s GNU >/dev/null && echo true || echo false) function portable_xargs_r() { if $gnuxargs ; then cat - | xargs -r """ $@ """ else cat - | xargs """ $@ """ fi } echo 'this' > foo echo '=== Expect one line' cat foo | portable_xargs_r echo "content: " echo '=== DONE.' cat </dev/null > foo echo '=== Expect zero lines' cat foo | portable_xargs_r echo "content: " echo '=== DONE.' 
+2
source

You can make sure that there is always at least one line in the input. This may not always be possible, but you will be surprised at how many creative ways you can do this.

0
source

Here's a quick and dirty xargs-r using a temporary file.

 #!/bin/sh t=$(mktemp -t xargsrXXXXXXXXX) || exit trap 'rm -f $t' EXIT HUP INT TERM cat >"$t" test -s "$t" || exit exec xargs " $@ " <"$t" 
0
source

A typical use case is as follows:

 find . -print0 | xargs -r -0 grep PATTERN 

Some versions of xargs do not have the -r flag. In this case, you can specify / dev / null as the first file name so that grep never passes an empty list of file names. Since the template will never be found in / dev / null, this will not affect the output:

 find . -print0 | xargs -0 grep PATTERN /dev/null 
0
source

Source: https://habr.com/ru/post/905615/


All Articles