[colug-432] Exit Status of First Program in Bourne Shell Pipeline

jep200404 at columbus.rr.com jep200404 at columbus.rr.com
Sat Dec 5 11:51:56 EST 2015


On Fri, 4 Dec 2015 11:24:52 -0600, Rick Hornsby <richardjhornsby at gmail.com> wrote:

> Forgive me because I’m not entirely sure I understand your goal. 
> It seems like you’re writing a wrapper that runs a script ...

Indeed, it is a wrapper invoked by an Ansible module.
It can run an arbitrary program, not just a script.

In my case the arbitrary command is rsync -i.
Any output means that rsync changed something.
So for rsync -i, the wrapper returns two pieces of 
information:

    1. Was anything changed?
    2. Did it fail?

which is the basic result information that an Ansible module 
should return, albeit in JSON format.

> ... and then checks to see whether it succeeded or not.

Yes and whether or not anything was output on stdout.
The output could be large.

> Maybe something like this?
> 
> command_output=$($@ 2> /dev/null)

> if [ -z "$command_output" ]; then

I think $() is not available in Bourne shell, but `` is.
What difference do you see between $@ being in 
double quotes or not? 

    command_output=`"$@" 2> /dev/null`

Arbitrary programs can spew large amounts of output,
which might overwhelm what a shell variable can hold.
I just tried rsync -i ... | wc manually and got:

    1688835 3432129 130238764

I tried command_output=`rsync -i ... 2> /dev/null` manually
and it worked in bash.
echo "$command_output" | wc reported big numbers.
I am surprised that it did not crash or truncate command_output.

On Fri, 4 Dec 2015 15:43:29 -0500, Eric Garver <eric.garver at gmail.com> wrote:

> I assume the output may be large so you're trying to avoid 
> redirecting to a file or variable.

Yes. Although the following is elegant, saving large output 
in a temporary file or shell variable makes me wince.

    command_output=`"$@" 2> /dev/null`
    > if [ -z "$command_output" ]; then

> n=`("$@" ; echo $? > returncode) | wc -c`
> first_error=`< returncode`

That works. 

I do not like the temporary file, but at least it is a small file, 
so that is a significant improvement over saving 
the possibly large output of "$@" in a temporary file.
It is also an improvement for avoiding the need for the wait.
It is also much easier to read than my code. That is a win.

Thanks Eric.

Your code definitely improves over what I had. I will use it.



More information about the colug-432 mailing list