help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: strange redirection error


From: Greg Wooledge
Subject: Re: strange redirection error
Date: Sun, 12 Sep 2021 20:13:08 -0400

On Mon, Sep 13, 2021 at 02:02:47AM +0200, Christoph Anton Mitterer wrote:
> The goal is to get the following in an portable (well as far as
> possible) way:
> 
> output="$(cmd1 | cmd2)"
> exitstatus1=...
> exitstatus2=...

I don't know what you mean by portable, exactly.  This is help-bash,
though, so we can initially assume that you are using bash.

The way you do this in bash is quite simple:

#!/bin/bash
output=$(cmd1 | cmd2)
exitstatus1=${PIPESTATUS[0]}
exitstatus2=${PIPESTATUS[1]}

Easy enough, right?

Now, when you say "portable", do you mean that you want a version that
works in POSIX sh?  The simplest way to do that is to introduce a temp
file or two.

#!/bin/sh
tmp1=$(mktemp) || exit
tmp2=$(mktemp) || exit
output=$(
  { cmd1 ; echo "$?" > "$tmp1"; } |
  { cmd2 ; echo "$?" > "$tmp2"; }
)
read -r exitstatus1 < "$tmp1"
read -r exitstatus2 < "$tmp2"
rm "$tmp1" "$tmp2"

# Of course, you will also want traps to remove the temp files in case
# of premature exit.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]