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

Eric Garver eric.garver at gmail.com
Fri Dec 4 15:43:29 EST 2015


I assume the output may be large so you're trying to avoid redirecting
to a file or variable. Otherwise I suggest you just redirect the first
command to temporary a file, i.e. mktemp.

That being said.. this may work..
It requires an intermediate file, but I think you can use a subshell to
avoid the named pipe and background/wait.

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


On Fri, Dec 04, 2015 at 11:45:31AM -0500, jep200404 at columbus.rr.com wrote:
> How would you improve the following script?
> 
>     #!/bin/sh
>     
>     # This script executes the arguments as a command,
>     # then outputs whether or not command output anything and
>     # whether or not command failed (crashed).
>     #
>     # Two lines are output:
>     # First line:
>     #     1 means command output something
>     #     0 means command did not change anything
>     # Second line:
>     #     1 means command failed (non-zero exit status)
>     #     0 means command exitted normally
>     
>     pipe=~/command_to_wc.pipe
>     rm -f "${pipe}"
>     mknod "${pipe}" p
>     "$@" >"${pipe}" 2>/dev/null &
>     pid="$!"
>     n=`wc -c <"${pipe}"`
>     if [ "$n" = '0' ]; then
>         echo 0 ;# command did not output anything
>     else
>         echo 1 ;# command output something
>     fi
>     if wait $pid; then
>         echo 0 ;# normal
>     else
>         echo 1 ;# failure
>     fi
>     rm -f "${pipe}"
> 
> I started with
> 
>     n=`"$@" | wc -c`
> 
> but I could not get the exit status of the "$@" command,
> so I split the pipeline into to two chunks using the named pipe
> to communicate between them. Can I get rid of the named pipe?
> 
> Need to:
>     run in plain old boring (but oh so portable) Bourne shell
>     so avoid nifty bash features such as but not limited to
>         PIPESTATUS
>         pipefail
> _______________________________________________
> colug-432 mailing list
> colug-432 at colug.net
> http://lists.colug.net/mailman/listinfo/colug-432


More information about the colug-432 mailing list